n Drupal 8 Use "menu-item--active-trail" to set active class in menu | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

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',
        ]
    %}

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook