I'm trying to render out a menu with its label in Drupal 8. I am able to get the menu and its links inside of a preprocess function using a helper function, but I can't locate the menu's title.

Here is how I'm getting the menu. I'm able to add the return value as a twig variable $variable['menu']['menu-name'] and render out an <ul> anywhere I need to.

function get_menu($menu_name) {
  $menu_tree = \Drupal::menuTree();
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
  $tree = $menu_tree->load($menu_name, $parameters);
  $manipulators = array(
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  $tree = $menu_tree->transform($tree, $manipulators);
  $menu = $menu_tree->build($tree);

  return array('#markup' => drupal_render($menu));
  • Btw. You should use \Drupal::service('renderer')->renderRoot() instead of drupal_render().
    – kenorb
    Aug 4, 2017 at 21:29

1 Answer 1


Here is the snippet to change the menu name:

 function example_preprocess_menu(&$variables) {
      $element = &$variables['items'];
      foreach ($element as &$item) {
        if ($item['original_link']->getMenuName() == 'menu-machine-name') {
        //For the menu label    
       $menu = entity_load('menu', 'menu-machine-name');
          $menu_label = $menu->label(); 
          if ($item['title'] == 'Example menu') {
            $item['title'] = 'New menu name';
  • 1
    Shreya, this will get the menu's machine name from a menu link and allow you to change the link's text, but it does not show me the menu's label/title.
    – Floyd
    Dec 13, 2016 at 4:37
  • 1
    if you print $item['title'] you will get the title of menu Dec 13, 2016 at 5:22
  • 1
    If I dump my $menu['#items']['title'] it's only the title of the link, not the menu.
    – Floyd
    Dec 13, 2016 at 8:03
  • 2
    You want the menu name not the menu link is it ?? Dec 13, 2016 at 8:10
  • 1
    Yes. I'm passing the menu's machine name to the get_menu() function in my question. It's returning a renderable version of the menu's items. I am trying to also capture and output the menu's name as a label/header for it on my page. Thanks for being helpful.
    – Floyd
    Dec 13, 2016 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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