8.5.x MenuLinkTree.php MenuLinkTree::build(array $tree)
8.0.x MenuLinkTree.php MenuLinkTree::build(array $tree)
8.1.x MenuLinkTree.php MenuLinkTree::build(array $tree)
8.2.x MenuLinkTree.php MenuLinkTree::build(array $tree)
8.3.x MenuLinkTree.php MenuLinkTree::build(array $tree)
8.4.x MenuLinkTree.php MenuLinkTree::build(array $tree)
8.6.x MenuLinkTree.php MenuLinkTree::build(array $tree)

Builds a renderable array from a menu tree.

The menu item's LI element is given one of the following classes:

  • expanded: The menu item is showing its submenu.
  • collapsed: The menu item has a submenu that is not shown.
  • leaf: The menu item has no submenu.


\Drupal\Core\Menu\MenuLinkTreeElement[] $tree: A data structure representing the tree, as returned from MenuLinkTreeInterface::load().

Return value

array A renderable array.

Overrides MenuLinkTreeInterface::build

1 method overrides MenuLinkTree::build()
ToolbarMenuLinkTree::build in core/modules/toolbar/src/Menu/ToolbarMenuLinkTree.php
Builds a renderable array from a menu tree.


core/lib/Drupal/Core/Menu/MenuLinkTree.php, line 157


Implements the loading, transforming and rendering of menu link trees.




public function build(array $tree) {
  $tree_access_cacheability = new CacheableMetadata();
  $tree_link_cacheability = new CacheableMetadata();
  $items = $this
    ->buildItems($tree, $tree_access_cacheability, $tree_link_cacheability);
  $build = [];

  // Apply the tree-wide gathered access cacheability metadata and link
  // cacheability metadata to the render array. This ensures that the
  // rendered menu is varied by the cache contexts that the access results
  // and (dynamic) links depended upon, and invalidated by the cache tags
  // that may change the values of the access results and links.
  $tree_cacheability = $tree_access_cacheability
  if ($items) {

    // Make sure drupal_render() does not re-order the links.
    $build['#sorted'] = TRUE;

    // Get the menu name from the last link.
    $item = end($items);
    $link = $item['original_link'];
    $menu_name = $link

    // Add the theme wrapper for outer markup.
    // Allow menu-specific theme overrides.
    $build['#theme'] = 'menu__' . strtr($menu_name, '-', '_');
    $build['#menu_name'] = $menu_name;
    $build['#items'] = $items;

    // Set cache tag.
    $build['#cache']['tags'][] = 'config:system.menu.' . $menu_name;
  return $build;