Drupal - Adding classes to menu items to signify what level they are

You can use theme_menu_link() in Drupal 7.

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

  $element['#attributes']['class'][] = 'depth-' . $element['#original_link']['depth'];

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

Here I added:

$element['#attributes']['class'][] = 'depth-' . $element['#original_link']['depth'];

Which will provide a class on the list item with the menu depth.


Modifying classes and markup in the menu structure is not very easy (at least not in Drupal 6 and I think Drupal 7 is the same). The problem is that in order to know what lever you are printing, you need to handle the creation of the menu pretty much by your self.

With the proper CSS, you don't need such indication, as you an use the nesting instead:

  • ul.menu li a Level 1
  • ul.menu ul li a Level 2
  • ul.menu ul ul li a Level 3

This is not elegant, and can make matter more complicated than needed, but it's a simpler solution than having to deal with the Drupal menu system.

Tags:

Navigation