Twig, loop filter

I have a loop in a branch:

{% for date in dates %}
    <li>{{date}}</li>
{% endfor %}

      

I need to use only 5 elements of my array (0-5) for this loop, after which for the second loop I need to use the next 5 elements (6-11), etc.

How can i do this?

+3


source to share


2 answers


you can use slice

{% for date in dates|slice(0, 5) %}
    <li>{{date}}</li>
{% endfor %}

      



for the next cycle

{% for date in dates|slice(5, 5) %}
    <li>{{date}}</li>
{% endfor %}

      

+5


source


You can use a slice

filter

{% for i in dates|slice(start, length) %}
    <li>{{date}}</li>
{% endfor %}

      



So, the first time you set start = 0

and length = 4

(if you need 5 items, you shouldn't iterate from 0 to 5 since the number is six), the next time you set and (if you need 5 items, you shouldn't iterate over from 0 to 5, since the number is six), the next time from 5 to 9, and so on ...

+2


source







All Articles