6

I have a structure section which I am using to create a navigation menu. It works ok and produces the list etc. I want to add a class to the li element if it has children.

Current Code is:

{% set entries = craft.entries.section('navigation') %}

<ul>
    {% nav entry in entries %}
        <li>

            {# Check for entry type / get related entry #}
            {% if entry.type == 'customLink' %}

                {# Link to a custom url #}
                <a href="{{ entry.customUrl }}">{{ entry.title }}</a>

            {% else %}

                {# Link to a structure entry #}
                <a href="{{ entry.url }}">{{ entry.title }}</a>

            {% endif %}

            {# Repeat this for child entries #}
            {% ifchildren %}
                <ul class="dropdown">{% children %}</ul>
            {% endifchildren %}

        </li>
    {% endnav %}
</ul>

I want to add class="has-dropdown" to the first list element if it has children.

I have tried this:

<li {% ifchildren %}class="has-dropdown"{% endifchildren %}>

But that does not work. How can this be achieved?

Lindsey D
  • 23,974
  • 5
  • 53
  • 110
mmc501
  • 1,779
  • 13
  • 34

2 Answers2

10

The Methods section on the EntryModel documentation page has a lot of useful things for working with navigation for Structure sections. You can use hasDescendants():

{% if entry.hasDescendants() %}class="has-dropdown"{% endif %}
Simon Kuran
  • 3,015
  • 1
  • 18
  • 33
  • Keep in mind, that this solution will even find child entries that are disabled, so you will have the class added even if there are only disabled pages within this part of the navigation tree. – Manuel Jul 01 '19 at 17:44
4

Try this:

<li {% if entry.level == 1 and entry.children|length %}class="has-dropdown"{% endif %}>
Christian Steger
  • 490
  • 3
  • 14