7

I am developing a theme for Drupal 7 and I am struck up with the following issue. I can see there are fixes through jQuery. But I would like to do it in the Drupal way.

My current HTML

<ul class="menu sf-js-enabled">
<li class="first leaf">
    <a href="/" class="active">Home</a></li>
<li class="last expanded">
    <a href="/node/57">About Us</a>
        <ul class="menu sf-js-enabled" style="display: none; visibility: hidden;">
            <li class="first leaf"><a href="/node/69">Contact Us</a></li>
            <li class="last leaf"><a href="/node/73">Typhygraphy</a></li>
        </ul>
</li>

And I want something like this

<ul class="menu sf-js-enabled">
<li class="first leaf active">
    <a href="/" class="active">Home</a></li>
<li class="last expanded">
    <a href="/node/57">About Us</a>
        <ul class="menu sf-js-enabled" style="display: none; visibility: hidden;">
            <li class="first leaf"><a href="/node/69">Contact Us</a></li>
            <li class="last leaf"><a href="/node/73">Typhygraphy</a></li>
        </ul>
</li>

The "active" class needs to be there in the <li> also.

11

You can achieve your goal without jQuery. Just use theme_menu_link() function, or (my suggestion) theme_menu_link__your_menu()

Place this function in your template.php file:

function YOURTHEME_menu_link(array $variables) {
    $element = $variables['element'];
    $sub_menu = '';

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);

    // if link class is active, make li class as active too
    if(strpos($output,"active")>0){
        $element['#attributes']['class'][] = "active";
    }
    return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

You can use this function only for menus displayed as a block. If you're theming main menu:

  1. go to admin/appearance/settings/yourtheme and turn the main menu off.
  2. go to admin/structure/block and place main menu block in header region
  3. customize ul with theme_menu_tree() and li elements with theme_menu_link()
1
  • Thank you @jack-pl. It is working perfectly as expected. May 25 '13 at 1:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.