2

I am trying to add a class which will cycle through on every iteration of a matrix block type, here is my code:

{% for block in entry.asideNavigation %}

    {% switch block.type %}

        {% case 'textBlock' %}
            <li class="aside__nav__item {{ cycle(['cs-a','cs-b'], loop.index0) }}">
                ...
            </li>

        {% case 'imageBlock' %}
            ...

    {% endswitch %}

{% endfor %}

This cycle function gives me the error "Variable "loop" does not exist" where am I going wrong?

  • That is weird, the code works fine for me. Have you tried isolating only this code? Maybe there's something wrong in the rest of your twig code that triggers this? – André Elvan Sep 17 '14 at 8:30
  • Weird, I thought it should work. Yes everything works fine if I remove the cycle function so it must be something to do with the loop in matrix field? – Gareth Sep 17 '14 at 8:34
  • If you try to just output {{ loop.index0 }} outside of the switch, does that work? Try removing everything else inside the for loop. – André Elvan Sep 17 '14 at 9:35
  • Yeah that works, its just when you put the {{ loop.index0 }} inside of the switch. – Gareth Sep 17 '14 at 9:39
  • It works inside a switch in my tests. And with the exact same cycle that you have. You sure there isn't some other twig code in the ... that messes with you? :) – André Elvan Sep 17 '14 at 9:58
3

This is mostly likely a scoping issue inside the switch statement. Try something like this:

{% for block in entry.asideNavigation %}

    {% set index0 = loop.index0 %}

    {% switch block.type %}

        {% case 'textBlock' %}
            <li class="aside__nav__item {{ cycle(['cs-a','cs-b'], index0) }}">
                ...
            </li>

        {% case 'imageBlock' %}
            ...

    {% endswitch %}

{% endfor %}
| improve this answer | |
  • Hi Brad, that was exactly the issue, thank you. – Gareth Sep 17 '14 at 18:45

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.