Drupal - How to add class in li element (for page where I am) in menu for drupal 8

To add active class to <li> need to add the following code in your .theme file and menu.html.twig

In .theme file add this

function themename_preprocess_menu(&$variables, $hook) {
  if ($hook == 'menu__main') { // If it is not working replace "main__menu" with "menu"

    // Get the current path.
    $current_path = \Drupal::request()->getRequestUri();
    $items = $variables['items'];
    foreach ($items as $key => $item) {
      // If path is current_path, set active to li.
      if ($item['url']->toString() == $current_path) {
      // Add active link.
      $variables['items'][$key]['attributes']['class'] = 'active';
      }
    }
  }
}

In menu.html.twig replace your <li> with below line.

replace this line

{{ link(item.title, item.url) }}

by

<li {{ item.attributes }} ><a  href="{{ item.url }}"  {{ item.attributes }} > {{ item.title }}</a></li>

It will be better if you programmatically detect the page and apply the class on that condition.You can follow the following steps.

  • Detect the current page ( CODE : For Drupal 7) .

     <php
      $path = current_path();
      $path_alias = drupal_lookup_path('alias',$path);
     ?>
    
  • Add the if condition matching your page name with that of current page

    if($path_alias == "current-page") { print  "active"; }
    

This may solve your issue

Tags:

Routes

8