3

I'm trying to use this code:

{% nav category in categories %}

   {{ category.title }}

   {% children %}

   {% if not loop.last %} BLAH {% endif %}

{% endnav %}

It appears that the {% if not loop.last %} conditional doesn't work inside of a {% nav %} tag.

How can I target/style the first and last items in each level of a nav structure?

2 Answers 2

5

Update Sorry, I originally thought you were building nav and just showing simplified code. If you just want to list the categories then this should work:

{% nav category in categories %}
    {{- category.title -}}
    {% if not loop.last %}, {% endif %}
    {% children %}
{% endnav %}

If your trying to build a nav system, then this should work. In either case just place your 'loop' before the children tag. See this answer for another example.

<ul id="nav">
    {% nav category in categories %}

        {% if loop.first %}
            <li class="first">
        {% elseif loop.last %}
            <li class="last">
        {% else %}
            <li>
        {% endif %}

            <a href="{{ category.url }}">{{ category.title }}</a>
            {% ifchildren %}
                <ul>
                    {% children %}
                </ul>
            {% endifchildren %}
        </li>
    {% endnav %}
</ul>
2
  • Alas, in this case, my loop logic needs to come before the {% children %} tag. Commented Feb 5, 2015 at 14:33
  • (On the other hand, I suppose I could rearrange it to use !loop.first instead of !loop.last...) Commented Feb 5, 2015 at 14:34
1

I ended up solving this with a recursive Twig macro:

{% macro catObj(category) %}
    ... blah ...
    {% if category.children | length %}
        {% for child in category.children %}
            {{ _self.catObj( child ) }}
            {% if not loop.last %},{% endif %}
        {% endfor %}
    {% endif %}
{% endmacro %}

{% for category in categories %}
    {{ _self.catObj( category ) }}
    {% if not loop.last %},{% endif %}
{% endfor %}

I appreciate Douglas and others pointing out that the loop variable is available in the {% nav %} tag before the {% children %} tag, but in this case it seemed like less work to use a macro than to jump through code-rearranging/variable-hoisting hoops.

1
  • I added another example that should do what you need much easier. Like I said, just put the 'loop' clause before the 'children' tag. Commented Feb 5, 2015 at 2:24

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.