You are here

public function TwigExtension::drupalMenu in Twig Tweak 8

Same name and namespace in other branches
  1. 8.2 src/TwigExtension.php \Drupal\twig_tweak\TwigExtension::drupalMenu()

Returns the render array for Drupal menu.

Parameters

string $menu_name: The name of the menu.

int $level: (optional) Initial menu level.

int $depth: (optional) Maximum number of menu levels to display.

Return value

array A render array for the menu.

File

src/TwigExtension.php, line 235

Class

TwigExtension
Twig extension with some useful functions and filters.

Namespace

Drupal\twig_tweak

Code

public function drupalMenu($menu_name, $level = 1, $depth = 0) {

  /** @var \Drupal\Core\Menu\MenuLinkTreeInterface $menu_tree */
  $menu_tree = \Drupal::service('menu.link_tree');
  $parameters = $menu_tree
    ->getCurrentRouteMenuTreeParameters($menu_name);

  // Adjust the menu tree parameters based on the block's configuration.
  $parameters
    ->setMinDepth($level);

  // When the depth is configured to zero, there is no depth limit. When depth
  // is non-zero, it indicates the number of levels that must be displayed.
  // Hence this is a relative depth that we must convert to an actual
  // (absolute) depth, that may never exceed the maximum depth.
  if ($depth > 0) {
    $parameters
      ->setMaxDepth(min($level + $depth - 1, $menu_tree
      ->maxDepth()));
  }
  $tree = $menu_tree
    ->load($menu_name, $parameters);
  $manipulators = [
    [
      'callable' => 'menu.default_tree_manipulators:checkAccess',
    ],
    [
      'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
    ],
  ];
  $tree = $menu_tree
    ->transform($tree, $manipulators);
  return $menu_tree
    ->build($tree);
}