Siblings Menu Block
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.
$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);
// Optional: Native sort and access checks.
$manipulators = [
['callable' => 'menu.default_tree_manipulators:checkNodeAccess'],
['callable' => 'menu.default_tree_manipulators:checkAccess'],
['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
];
$tree = $menu_tree->transform($tree, $manipulators);
// Finally, build a renderable array and enable proper caching.
$menu = $menu_tree->build($tree);
$build = [
'#markup' => \Drupal::service('renderer')->render($menu),
'#cache' => [
'contexts' => ['url'], // For .active classes.
'tags' => ['config:system.menu.' . $menu_name], // For menu changes.
],
];
return $build;