0

I think I am doing exactly the same as here but I only get the "even" class at each iteration.

{% for block in entry.articlebody %}

    {% set index0 = loop.index0 %}

    {% switch block.type %}

        {% case 'heading' %}
            <h2 class="section-title">{{ block.heading }}</h2><!-- /.section-title -->

        {% case 'text' %}
            <div class="{{ cycle(['odd', 'even'], index0) }}">{{ block.text }}</div>    

    {% endswitch %}
{% endfor %}
2

The loop.index0 variable will be incremented for each block, regardless of type, so assuming every other block is a header, it's not surprising that the cycle method prints "even" for every text block.

I think what you need is a different variable which only increments whenever you hit a text block (note that this variable should be declared outside the for loop):

{% set textIndex = 0 %}

{% for block in entry.articlebody %}

    {% switch block.type %}

        {% case 'heading' %}
            <h2 class="section-title">{{ block.heading }}</h2><!-- /.section-title -->

        {% case 'text' %}
            <div class="{{ cycle(['odd', 'even'], textIndex) }}">{{ block.text }}</div>
            {% set textIndex = textIndex + 1 %}

    {% endswitch %}
{% endfor %}
  • Works like a charm, Mats! Seems like I need to dig deeper into the Twig docs:-) – Nutmeg Nov 8 '16 at 0:57

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.