Skip to content

Instantly share code, notes, and snippets.

@kevinquillen
Created December 7, 2012 18:02
Show Gist options
  • Save kevinquillen/4235124 to your computer and use it in GitHub Desktop.
Save kevinquillen/4235124 to your computer and use it in GitHub Desktop.
Adding menu names to the ul menus in Drupal 7
function themename_menu_link(&$variables) {
$element = $variables['element'];
$sub_menu = '';
$element['#attributes']['data-menu-parent'] = $element['#original_link']['menu_name'] . '-' . $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";
}
function themename_preprocess_menu_tree(&$variables) {
$tree = new DOMDocument();
$tree->loadHTML($variables['tree']);
$links = $tree->getElementsByTagname('li');
$parent = '';
foreach ($links as $link) {
$parent = $link->getAttribute('data-menu-parent');
}
$variables['menu_parent'] = $parent;
}
function themename_menu_tree(&$variables) {
return '<ul class="menu ' . $variables['menu_parent'] . '">' . $variables['tree'] . '</ul>';
}
@kevinquillen
Copy link
Author

A novel approach to getting the menu name applied to the UL container of a Drupal menu, with a depth added. This grants you the ability to get better names on the ul menus instead of 'menu' for better targeting with say, Javascript.

@henrijs
Copy link

henrijs commented Aug 13, 2013

Thank you very much for this approach. It's pure genius. I'll take "novel" over "theme_menu_tree" any day. Forked your gist and fixed couple of bugs. 1) @ before $tree->loadHTML() will get rid of errors about HTML5 tags (are those from new DOMDocument()?) and most importantly big one b) break in foreach loop will return correct $parent value (first li, not last, since last one is deepest level in deeper nested trees).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment