phploopsfor-looptwigtwig-filter

Targeting every nth index from x to y in Twig


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:

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.


Solution

  • You can check the rest of the division. Here a working solutions:

    {% for i in 1..30 %}
     {% set class = 'green' %}
     {% set loop_index = loop.index %}
     {% if (loop_index %7 >= 1 and loop_index %7 < 5) %}
       {% set class = 'orange' %}
     {% endif %}
        * {{ i }} {{class}}
    {% endfor %}
    

    This will output as:

    * 5 green
    * 6 green
    * 7 green
        * 8 orange
        * 9 orange
        * 10 orange
        * 11 orange
    * 12 green
    * 13 green
    * 14 green
        * 15 orange
        * 16 orange
        * 17 orange
        * 18 orange
    * 19 green
    * 20 green
    * 21 green
        * 22 orange
        * 23 orange
        * 24 orange
        * 25 orange
    * 26 green
    * 27 green
    

    You can check the output in this working twigfiddle