2

I'm trying to display a menu in my module. I've used \Drupal::entityManager()->getStorage('menu')->load('oz-topbar-menu'); which allows me to get the title of the menu, the description, etc.

I obviously need the links of that menu, and I can't understand how to retrieve. From what I've read in the documentation I should probably use MenuLinkTreeInterface but I don't understand how to instantiate it.

I've tried \Drupal::menuTree()->load('oz-topbar-menu', $menu_parameters);. With basic menu parameters it returns a humongous amount of information; I'm guessing it must be the entire menu tree of Drupal.

I tried playing with the parameters of MenuTreeParameters (setTopLevelOnly, setRoot('oz-topbar-menu')) but it returns an empty array.

I've tried sending this as a MenuTreeParameters object with \Drupal::menuTree()->getCurrentRouteMenuTreeParameters('oz-topbar-menu'), but I still get a massive link tree.

1 Answer 1

4

You are probably just missing the build() call.

$menu_name = 'my-custom-menu';
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$renderable = \Drupal::menuTree()->build($tree);
print \Drupal::service('renderer')->render($renderable);

Core is the best example for these kinds of things. I pulled the above from SystemMenuBlock::build().

2
  • Alright, I'll try that tomorrow morning. Thank you! Commented Jan 25, 2015 at 4:12
  • Beautiful, that did the trick. Commented Jan 26, 2015 at 18:22

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.