Search code examples
matrixtwigcraftcms

matrix twig loop rows - odd one color and even alternating colors


I'm trying to loop through rows that result in the following:

row 1 - white
row 2 - gray
row 3 - white
row 4 - navy
row 5 - white
row 6 - gray 
row 7 - white
row 8 - navy

And etc...

I have the following, which obviously only works for the first 5 rows, but can't seem to figure out the correct way to do this:

{% if loop.index is odd %}
    <div id="{{ target }}" class="band white">
{% elseif loop.index == 2 %}
    <div id="{{ target }}" class="band gray">
{% elseif loop.index == 4 %}
    <div id="{{ target }}" class="band navy">
{% endif %}

any help is appreciated. Thanks!


Solution

  • You may want to check out the cycle function, and use it like this:

    class="band {{ cycle(["white", "gray", "white", "beige"], loop.index0) }}"