Drupal 8 - Display submenu in a block

Posted on 19 Mar 2016 by Oleksii Raiu
To edit and place a submenu in a block in Drupal 8, place this code in the block plugin class file:

   * {@inheritdoc}
public function build() {
$menu_tree = \Drupal::menuTree();
$menu_name = 'main';
$parameters = new MenuTreeParameters();
$tree = $menu_tree->load($menu_name, $parameters);
$manipulators = array(
'callable' => 'menu.default_tree_manipulators:checkAccess'),
'callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
$tree = $menu_tree->transform($tree, $manipulators);
$subtree = $tree['SUBTREE IDENTIFIER GOES HERE']->subtree;
$menu = $menu_tree->build($subtree);
    foreach (
$menu['#items'] as &$item) {
$item['url']->setOption('fragment', 'block-aboutussubmenu');
$markup = \Drupal::service('renderer')->render($menu);

$build = array(
'#type' => 'markup',
'#markup' => $markup,



In this case, a fragment was added to each link.

Update: How do you get the "subtree identifier" you need? I view the $tree variable in a debugger. Alternatively, you can install the devel module and dsm($tree) to see the whole menu tree and choose the kays you need.