Skip to content

Instantly share code, notes, and snippets.

@karlosgliberal
Last active May 11, 2016 14:53
Show Gist options
  • Select an option

  • Save karlosgliberal/7813b19e61d00d4bebc3962a8f59d918 to your computer and use it in GitHub Desktop.

Select an option

Save karlosgliberal/7813b19e61d00d4bebc3962a8f59d918 to your computer and use it in GitHub Desktop.
Extension Twig Menu
<?php
// @file modules/custom/my_module/src/Twig/MyModuleExtension.php
/**
* Provides function to programmatically rendering a menu
*
* @param String $menu_name
* The machine configuration id of the menu to render
*/
public function render_menu(string $menu_name) {
$menu_tree = \Drupal::menuTree();
// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
// Load the tree based on this set of parameters.
$tree = $menu_tree->load($menu_name, $parameters);
// Transform the tree using the manipulators you want.
$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);
// Finally, build a renderable array from the transformed tree.
$menu = $menu_tree->build($tree);
return array('#markup' => drupal_render($menu));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment