Code snippet that can be used to set active class in menu using "menu-item--active-trail" in Drupal 8.
/**
* Implements hook_preprocess_menu() for menu.html.twig.
*/
function themename_preprocess_menu(&$variables, $hook) {
if ($hook == 'menu') {
$current_path = \Drupal::request()->getRequestUri();
foreach ($variables['items'] as &$item) {
if ($item['in_active_trail']) {
if ($item['url']->toString() == $current_path) {
$item['is_active'] = TRUE;
} elseif (count($item['below'])) {
_themename_menu_process_submenu($item['below'], $current_path);
}
}
}
}
}
/**
* Set active and active-trail class for sub-menus recursively.
*/
function _themename_menu_process_submenu(&$submenu, $current_path) {
foreach ($submenu as &$item) {
if ($item['in_active_trail']) {
if ($item['url']->toString() == $current_path) {
$item['is_active'] = TRUE;
} elseif (count($item['below'])) {
_themename_menu_process_submenu($item['below'], $current_path);
}
}
}
}
and in twig file menu--main.html.twig just use:
{%
set item_classes = [
'menu',
item.in_active_trail ? 'active-trail',
item.is_active ? 'active',
]
%}