1

How do you add a class to menu items that are not expanded (or don't have children)?

    {% for item in items %}
      {%
        set classes = [
          item.is_expanded ? 'menu-item--expanded dropdown panel simple-dropdown',
          item.is_collapsed ? 'collapsed',
          item.in_active_trail ? 'active',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}

Edit: Can anyone point me into getting the answer provided, implemented in my example?

3

I think you can do some cool things when you set classes. A colon : indicates 'else'.

{%
  set classes = [
    item.is_expanded ? 'is-expanded' : 'not-expanded',
    item.is_collapsed ? 'is-collapsed' : 'not-collapsed',
    item.in_active_trail ? 'active',
    item.below ? 'has-children': 'no-children',
  ]
%}

EDIT: Added ', after no-children

  • 1
    Missing single quote and comma after « 'no-children ». – Bisonbleu Jun 14 '19 at 12:46
3

Since Twig builds out the menu recursively the only way (I've found) to do this is to first check if the current item has any active children, and add a class to it once that is determined. So, before the li is posted, check if it has any children. Something like:

{% for child in item.below %}
  {% set children = item.below ? '1': '0' %}

  {% if children %}
    {# the current item has expanded/active children #}
  {% else %}
    {# the current item has no children #}
    {% set classes = classes|merge(['no_active_children']) %}
  {% endif %}

  <li{{ item.attributes.addClass(classes) }}>{{ link(item.title, item.url) }}
    {% if item.below %}
        {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
    {% endif %}
  </li>
{% endfor %}

Hope that helps.

  • Would you care to add the {% for item in items %} loop to your example? I can't seem to get it to work! Thanks. – Pim Feb 14 '17 at 11:35
  • Yes, my mistake. Hopefully that should work now. – Rina Feb 15 '17 at 14:00
  • I add your code right after my set classes array - but no go. – Pim Feb 19 '17 at 21:15
  • The code above is missing an opening {% if %} as well as a closing {% endfor %}. Fixed. – Bisonbleu Jun 14 '19 at 13:02

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.