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?

2 Answers 2

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
  • 1
    Missing single quote and comma after « 'no-children ».
    – Bisonbleu
    Commented Jun 14, 2019 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.

4
  • 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
    Commented Feb 14, 2017 at 11:35
  • Yes, my mistake. Hopefully that should work now.
    – Rina
    Commented Feb 15, 2017 at 14:00
  • I add your code right after my set classes array - but no go.
    – Pim
    Commented Feb 19, 2017 at 21:15
  • The code above is missing an opening {% if %} as well as a closing {% endfor %}. Fixed.
    – Bisonbleu
    Commented Jun 14, 2019 at 13:02

Your Answer

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

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