How to set a custom class to submenus I am working on sidebar menu in a Custom Drupal 8 Theme. I am trying to set a class of sidebar__menu--submenu-1,sidebar__menu--submenu-2, sidebar__menu--submenu-3 and so on depending on the level of the submenus.

So far, I was able to add the class sidebar__menu to the first level &amp; sidebar__menu--submenu to all the submenus. However, I want to add the class sidebar__menu--submenu-(number of the level) so I can style &amp; control the sidebar better on css.

Any help will be really appreciate it!

Here it is my code menu.html.twig:

{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level, menu_name) %}
  {% import _self as menus %}
  {%
    set menu_classes = [
      'sidebar__menu' ~ menu_name|clean_class,
    ]
  %}
  {%
    set submenu_classes = [
      'sidebar__menu' ~ menu_name|clean_class ~ '--submenu',
    ]
  %}
  {% if items %}
    {% if menu_level == 0 %}
      &lt;ul{{ attributes.addClass('container mx-auto', menu_classes) }}&gt;
    {% else %}
      &lt;ul {{ attributes.removeClass(menu_classes).addClass(submenu_classes) }}&gt;
    {% endif %}

    {% for item in items %}
     {%
      set classes = [
        'sidebar__item',
        item.is_expanded ? 'sidebar__item--expanded',
        item.is_collapsed ? 'sidebar__item--collapsed',
        item.in_active_trail ? 'sidebar__item--active-trail',
      ]
      %}
      &lt;li{{ item.attributes.addClass(classes) }}&gt;
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      &lt;/li&gt;
    {% endfor %}
    &lt;/ul&gt;
  {% endif %}
{% endmacro %}
Here's one way to modify your code to add a unique class for each menu level dynamically:


Add a new class appended with the value of menu_level plus one:


  {%
    set submenu_classes = [
      'sidebar__menu' ~ menu_name|clean_class ~ '--submenu',
      'sidebar__menu--submenu-' ~ (menu_level + 1),
    ]
  %}



Remove the previously added class, otherwise I believe it will add the class for each level incrementally. 


    {% if menu_level == 0 %}
      &lt;ul{{ attributes.addClass('container mx-auto', menu_classes) }}&gt;
    {% else %}
      &lt;ul{{ attributes.removeClass(menu_classes, 'sidebar__menu--submenu-' ~ (menu_level)).addClass(submenu_classes) }}&gt;
    {% endif %}