For one of my projects, I have to create a tree menu, with parents and children, that would be used to navigate through the website. The parents are collapsible. Below is the twig file that I am using to generate the menu:

{% macro menu_links(menu_tree, route_tid, current_depth, max_depth, collapsible) %}
{% import _self as macros %}
{% for item in menu_tree %}
    set liClass = [
      item.subitem and current_depth < max_depth ? 'menu-item menu-item--expanded block-taxonomymenu__menu-item block-taxonomymenu__menu-item--expanded' : 'menu-item block-taxonomymenu__menu-item',
      route_tid == item.tid ? 'menu-item--active block-taxonomymenu__menu-item--active' : ''

  <li class="{{ liClass|join(' ') }}">
    {% if item.image %}
      <img class="menu-item-image block-taxonomymenu__image" src="{{ item.image }}" {% if item.use_image_style == false %}height="{{ item.height }}" width="{{ item.width }}"{% endif %} />
    {% endif %}
    <span class="levels">
      <a href="{{ item.url }}" class="block-taxonomymenu__link {% if route_tid == item.tid %}active block-taxonomymenu__link--active{% endif %}">{{ item.name }}{% if item.show_count == true %} [{{ item.nodes|length }}]{% endif %}</a>
    {% if item.subitem and current_depth < max_depth %}
      {% if item.interactive_parent %}
        <i class="far fa-plus-square parent-toggle" aria-hidden="true"></i>
      {% endif %}
      {% if collapsible == TRUE %}
        <ul class="menu block-taxonomymenu__submenu collapsed-submenu">
      {% else %}
        <ul class="menu block-taxonomymenu__submenu">
      {% endif %}
        {{ macros.menu_links(item.subitem, route_tid, current_depth + 1, max_depth, collapsible) }}
    {% endif %} 
{% endfor %}

{% endmacro %}

I wanted to know if it was possible to add an extra class to the last li class of the tree menu? I have actually tried to add current_depth == max_depth ? 'item--last': '' in the setliClass and {% if current_depth == max_depth %}item--last{% endif %}" in the li class="{{ liClass|join(' ') }}" part, but this is not working.

1 Answer 1


You should be able to apply an additional loop to iterate by specific menu_level. Here is an example of a twig template that iterates over menu level variable: How to add classes to menu items in navigation twig template

Then use a condition to set the class within the for loop such as:

loop.last ? 'last'

See all the variables associated with for loops in twig here: https://twig.symfony.com/doc/2.x/tags/for.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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