Monday, October 31, 2011

Adding unique CSS classes to primary menu elements

Adding unique CSS classes to primary menu elements in a Drupal theme is quite easy. You just need to override the theme_menu_link function in the template.php.

I'm working on a Fusion sub-theme named nebula. So the function is named nebula_menu_link .
/**
 * Manually add unique CSS classes to primary menu li elements
 * @staticvar int $item_id
 * @param type $variables
 * @return type 
 */
function nebula_menu_link($variables) {
  $element = $variables['element'];

  static $item_id = 0;
  $element['#attributes']['class'][] = 'nv_' . (++$item_id);
  $sub_menu = $element['#below'] ? drupal_render($element['#below']) : '';

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  return '' . $output . $sub_menu . '';
}

Refer to line #11 that's where the meat of the function. The line adds a "nv_1" class to the first primary menu element. It should be easy to figure out that the succeeding elements would be "nv_2", "nv_3". That's the (++$item_id).

Here's how it would look when theme renders.
<ul class="menu">
      <li class="first leaf nv_1">
          <a href="/" class="active">Home</a>
      </li>
      <li class="leaf nv_2">
          <a href="/content/about-us" title="">About Us</a>
      </li>
      <li class="leaf nv_3">
          <a href="/content/solutions" title="">Solutions</a>
      </li>
      <li class="leaf nv_4">
          <a href="/content/services">Services</a>
      </li>
      <li class="leaf nv_5">
          <a href="/" title="" class="active">News</a>
      </li>
      <li class="leaf nv_6">
          <a href="/" title="" class="active">Library</a>
      </li>
      <li class="last leaf nv_7">
          <a href="/content/contact-us" title="">Contact</a>
      </li>
  </ul>

Now we can target individual li elements of the primary menu. Theme away!

No comments:

Post a Comment