I'm having a problem with the loop.index
in a for
loop for a complex grid (marked up as a simple single level HTML list). I have a loop_index
variable in a twig partial for a grid "cell" (a <li>
) which is equal to loop.index
.
Initially I had this simple specific numbers based check for the first items in the loop.
{% set class = 'green' %}
{% if (loop_index > 1 and loop_index < 5) or (loop_index > 7 and loop_index < 12) %}
{% set class = 'orange' %}
{% endif %}
But now it should be extended to include possibly unlimited number of items in the loop. Therefore not only items 2-4 and 8-11 would become orange
, but also 15-18 etc.
Basically I need to cycle through 2 classes (orange, green) in this way:
- 2-4 - orange
- (repeating pattern begins from here:)
- 5-7 - green (batch of 3)
- 8-11 - orange (batch of 4)
- 12-14 - green (batch of 3)
- 15-18 - orange (batch of 4)
- 19-21 - green (batch of 3)
- 22-25 - orange (batch of 4)
- ...
I tried to employ batch
and cycle
for that, but they seem to be inappropriate for this. batch
doesn't seem to work with "unlimited" loops and cycle
seems not ok for a repeated pattern with batches of same items (as opposed to looping through ungrouped single items). divisible by
also didn't work for me as needed in this case.
How can I change the classes depending on the value of loop.index
? I can't work with the for
loop or outside of it here — all the work needs to be done inside the grid "cell" partial.
You can check the rest of the division. Here a working solutions:
This will output as:
You can check the output in this working twigfiddle