1

I have this code:

{% for entry in craft.entries.section('gigs') %}
    <h2 class="{{ cycle(['odd','even'], loop.index0) }}">{{ entry.title }}</h2>
{% endfor %}

This returns the same cycles for the last two entries like so:

<h2 class="odd">Title 1</h2>
<h2 class="even">Title 2</h2>
<h2 class="odd">Title 3</h2>
<h2 class="even">Title 4</h2>
<h2 class="odd">Title 5</h2>
<h2 class="odd">Title 6</h2>

No matter how many entries, the last two entries have always the same class. Why is that?

Edit: Okay, I figured the problem. It's not a bug:

I filter the entries by date:

{% set present = now|date_modify("-1 day") %}
{% for entry in craft.entries.section('gigs') %}
   {% if entry.datum < present %}
       <h2 class="{{ cycle(['odd','even'], loop.index0) }}">{{ entry.title }</h2>
    {% endif %}
 {% endfor %}    

so the cycle filter works, but since some entries are filtered the odd/even schema doesn't work any longer. I guess I have to filter the entries first and then apply the cycle filter. But how would I have to write do that?

  • 1
    That is odd (see what I did there?). No, jokes aside, I'm not seeing this behavior when using the exact same code you're using. I suspect this is a bug that should be sent to P&T support. – André Elvan Feb 8 '15 at 14:23
  • Works fine here as well. Have you tried printing the index {{ loop.index0 }} — I believe that is what determines which value is ultimately used. – Douglas McDonald Feb 8 '15 at 16:55
  • 1
    We're not doing anything on top of Twig's cycle implementation. Maybe there is some additional template code affecting it that you didn't share? – Brad Bell Feb 8 '15 at 18:27
3

As you already found out, the loop.index counter increments for each iteration of the loop, not only if you use or print it within your conditional. The best solution to work against it is to get rid of that conditional.

In this case it is in fact possible to catch only those entries you are after, making the conditional redundent

{% for entry in craft.entries.section('gigs').datum('< ' ~ present) %}
    <h2 class="{{ cycle(['odd','even'], loop.index0) }}">{{ entry.title }</h2>
{% endfor %}

if it wasn't, you could have done your own counter that increments within the conditional.

{% set index = 0 %}
{% for entry in craft.entries.section('gigs') %}
    {% if entry.datum < present %}
        {% set index = index + 1 %}
        <h2 class="{{ cycle(['odd','even'], index) }}">{{ entry.title }</h2>
    {% endif %}
{% endfor %}

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.