Skip to main content

Get active trails in expanded menu

On one drupal site, I use a multilevel menu as the main menu and set it to 'expand all' in the menu block settings. I don't know, if this is the usual behaviour - but with this setup I  loose the active trails indicator on the menu array in twig. It took some while to find a solution for this problem ... here are the functions:

/**

* Implements hook_preprocess_menu().

*/

function zzz_helpers_preprocess_menu(&$var, $hook) {

// Get the current path.

$currentRoute = \Drupal::routeMatch()->getRouteName();

$currentParams = \Drupal::routeMatch()->getRawParameters();

$params = [];

foreach ($currentParams as $k => $v) {

$params[$k] = $v;

}

 

$menu_link_manager = \Drupal::service('plugin.manager.menu.link');

$menu_link = $menu_link_manager->loadLinksByRoute($currentRoute, $params);

 

if (is_array($menu_link) && count($menu_link)) {

$uuid = key($menu_link);

$menu_link = reset($menu_link);

if ($menu_link->getParent()) {

$parents = $menu_link_manager->getParentIds($menu_link->getParent());

}

$parents[$uuid] = $uuid;

}

_zzz_active_trail_helper($var['items'], $parents);

}

 

function _zzz_active_trail_helper(&$menu, $parents) {

foreach ($menu as $key => $item) {

if (in_array($key, $parents)) $menu[$key]['attributes']['class'] = 'current';

if (!empty($item['below'])) {

$arr = $menu[$key]['below'];

_zzz_active_trail_helper($arr, $parents);

$menu[$key]['below'] = $arr;

}

}

}