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

Comments

Add new comment

Restricted HTML

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

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

Web Posts

Search

Page Facebook