1

I want to output some code after the 10th top level category in a category listing. For example...

  • 1.
    • 1.1.
    • 1.2.
  • 2.
    • 2.1.
  • 3.
  • ...
  • 10.
  • Zoiks!

The problem is, I can't use Twig's loop.index in a conditional because it counts each of the children too (like a flat list). How can I test for the 10th top-level category?

{% nav category in craft.categories.group('categoryGroup') %}
  <li>
    <a href="{{ category.url }}">{{ category.title }}</a>
    {% ifchildren %}
      <ul>
        {% children %}
      </ul>
    {% endifchildren %}
  </li>
  {% if category.level == 1 and loop.index == 10 %}
    <li>Zoiks! That‘s a lot of categories!</li>
  {% endif %}
{% endnav %}
2

I think you'll just need to put it before the {% children %} tags. Something like:

{% nav category in craft.categories.group('categoryGroup') %}
    <li>

        <a href="{{ category.url }}">{{ category.title }}</a>

        {% if category.level == 1 and loop.index == 10 %}
            <li>Zoiks! That‘s a lot of categories!</li>
        {% endif %}

        {% if category.level == 1 %}
            {% set topLevelIndex = topLevelIndex + 1 %}
        {% endif %}

        {% ifchildren %}
            <ul>
                {% children %}
            </ul>
        {% endifchildren %}
    </li>
{% endnav %}
  • Works! Thanks, I thought I was going crazy. Is there are reason putting it before the {% children %} tag works? – Alex Roper Feb 3 '15 at 21:16
  • 1
    {% children %} is where things start to get recursive behind the scenes so variable scoping comes into play and topLevelIndex never gets updated. – Brad Bell Feb 3 '15 at 21:19
2

Maybe you can add in a little counting magic of your own:

{# before the nav tag #}
{% set topLevelIndex = 1 %}

{# inside nav loop #}
{% if category.level == 1 and topLevelIndex == 10 %}
    <li>Zoiks! That‘s a lot of categories!</li>
{% endif %}
{% if category.level == 1 %}
    {% set topLevelIndex = topLevelIndex + 1 %}
{% endif %}

This code hasn't been tested...

  • That's the workaround I tried initially, but topLevelIndex never goes past 2. I tested it by putting {{ topLevelIndex }} right after trying to increment it. I have set topLevelIndex = 1 outside the nav tag and set topLevelIndex = topLevelIndex + 1 is inside the nav tag loop. – Alex Roper Feb 3 '15 at 12:33
  • I think this might be a bug with the nav tag. If I try the same counter method using a for loop instead of the nav tag, it works as expected. – Alex Roper Feb 3 '15 at 12:38
  • Aha. Maybe someone from P&T can explain that better for us :) – naboovalley Feb 3 '15 at 12:51

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.