7

I would like to add class in li element in menu for drupal 8 for page where I am. For example if i am on page Start, that li have active class. Or If I am on Join page that li element for join have active class.

<ul class="">
<li class="active"><a href="#" >START</a></li>
<li class=""><a href="#" >About</a></li>
<li class=""><a href="#" >join</a></li>
</ul>

So, How to ask if li is active or no?

{% for item in items %}
  {% if item=SOMETHING %}
    <li class="active">
      <a  href="{{ item.url }}">{{ item.title }}</a>
    </li>
  {% else %}
    <li >
      <a  href="{{ item.url }}">{{ item.title }}</a>
    </li>
{% endfor %}
  • try first with css only li a:active { color:red; text-decoration:underline; } – No Sssweat Feb 18 '16 at 11:37
  • Soryy I didnt ask question good. :( I would like to add class=active for page where i am. – SakaSerbia Feb 18 '16 at 11:50
  • I actually got that, but try my css code to see if it works. (it might auto detect the page you are on and underline the Menu li accordingly) – No Sssweat Feb 18 '16 at 11:53
  • Is work but when you click on menu item and muve him prntscr.com/a4tpmy its seem that auto detection dont work. – SakaSerbia Feb 18 '16 at 12:03
  • why would anyone do that? you really think your users will do that? – No Sssweat Feb 18 '16 at 12:10
10

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>
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.