Drupal 7 custom menu rendering

3.4k views Asked by At

I am new to druapl theme development. Created hierarchical menu from drupal admin. I want to render this menu in my page.tpl.php file. I have used following code, But its not rendering submenus. Its not that its showing them as display none, But they are (sub menus) not rendered at all.

$params = array(
  'links' => menu_navigation_links('menu-eschopper-main-menu'),
  'attributes' => array(
    'class'=> array('nav','navbar-nav','collapse', 'navbar-collapse'),
  ),
);
print theme('links', $params);
2

There are 2 answers

3
Anthony Leach On

The function you are using 'menu_navigation_links' only displays links for a single level. You would be better looking at either the menu block module (https://www.drupal.org/project/menu_block) or using functionality such as the example below:

/**
 * Get a menu tree from a given parent.
 *
 * @param string $path
 *   The path of the parent item. Defaults to the current path.
 * @param int $depth
 *   The depth from the menu to get. Defaults to 1.
 *
 * @return array
 *   A renderable menu tree.
 */
function _example_landing_get_menu($path = NULL, $depth = 1) {
  $parent = menu_link_get_preferred($path);
  if (!$parent) {
    return array();
  }

  $parameters = array(
    'active_trail' => array($parent['plid']),
    'only_active_trail' => FALSE,
    'min_depth' => $parent['depth'] + $depth,
    'max_depth' => $parent['depth'] + $depth,
    'conditions' => array('plid' => $parent['mlid']),
  );

  return menu_build_tree($parent['menu_name'], $parameters);
}

This function will return a menu tree starting at a given url for a given depth.

The following code will produce a sub menu, with the current page as a parent and show child items up to a depth of 2.

$menu = _example_landing_get_menu(NULL, 2);
print render($menu);
0
zessx On

I used to do it manually, to have a perfect control on the rendering. You can use menu_tree_all_data() to load your menu links, and use a foreach on it:

template.php

function render_menu_tree($menu_tree) {
    print '<ul>';
    foreach ($menu_tree as $link) {
        print '<li>';
        $link_path = '#';
        $link_title = $link['link']['link_title'];
        if($link['link']['link_path']) {
            $link_path = drupal_get_path_alias($link['link']['link_path']);
        }
        print '<a href="/' . $link_path . '">' . $link_title . '</a>';
        if(count($link['below']) > 0) {
            render_menu_tree($link['below']);
        }
        print '</li>';
    }
    print '</ul>';
}

page.tpl.php

$main_menu_tree = menu_tree_all_data('menu-name', null, 3);
render_menu_tree($main_menu_tree);

Use menu_tree_all_data('menu-name') instead if you don't want to use a depth limitation.