Skip to main content
3 of 7
deleted 4 characters in body
leymannx
  • 18.8k
  • 6
  • 72
  • 126

With the help of @Icubes answer and MenuLinkTreeInterface::getCurrentRouteMenuTreeParameters we can simply get the current route's active menu trail. Having that we also have the parent menu item. Setting that as starting point via MenuTreeParameters::setRoot to build a new tree gives you the desired siblings menu.

// Enable url-wise caching.
$build = [
  '#cache' => [
    'contexts' => ['url'],
  ],
];

$menu_name = 'main';
$menu_tree = \Drupal::menuTree();

// This one will give us the active trail in *reverse order*.
// Our current active link always will be the first array element.
$parameters   = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
$active_trail = array_keys($parameters->activeTrail);

// But actually we need its parent.
// Except for <front>. Which has no parent.
$parent_link_id = isset($active_trail[1]) ? $active_trail[1] : $active_trail[0];

// Having the parent now we set it as starting point to build our custom
// tree.
$parameters->setRoot($parent_link_id);
$parameters->setMaxDepth(1);
$parameters->excludeRoot();
$tree = $menu_tree->load($menu_name, $parameters);

// Finally, build a renderable array.
$menu = $menu_tree->build($tree);

$build['#markup'] = \Drupal::service('renderer')->render($menu);

return $build;
leymannx
  • 18.8k
  • 6
  • 72
  • 126