Twig
Twig copied to clipboard
Adjust `cycle` implementation
Update code following #4158
- return mixed
- trigger when non countable
- type the position argument
Add doc precisions
~~All fixed~~
Documentation states it "cycles over" .. and we see it behaves more as a "static modulo-accessor".
I was wonderning if this function could return (or act as) an iterator ?
@smnandre the common use case is to use this cycle inside the body of a loop, using loop.index as position. The cycle function is not the one controlling the iteration behavior (if you want to iterate over the array passed as input, you don't need a function for that as the for loop can work with the array directly)
@smnandre the common use case is to use this
cycleinside the body of a loop, usingloop.indexas position. The cycle function is not the one controlling the iteration behavior (if you want to iterate over the array passed as input, you don't need a function for that as the for loop can work with the array directly)
This is what i was thinking of .. would it be possible to not pass the "position" ?
{% for turtle in turtles %}
🐢 {{ cycle([ '🔵', '🔴', '🟠', '🟣']) }}
{% endfor %}
{# would render #}
🐢 🔵 🐢 🔴 🐢 🟠 🐢 🟣
@smnandre the common use case is to use this
cycleinside the body of a loop, usingloop.indexas position. The cycle function is not the one controlling the iteration behavior (if you want to iterate over the array passed as input, you don't need a function for that as the for loop can work with the array directly)This is what i was thinking of .. would it be possible to not pass the "position" ?
{% for turtle in turtles %} 🐢 {{ cycle([ '🔵', '🔴', '🟠', '🟣']) }} {% endfor %} {# would render #} 🐢 🔵 🐢 🔴 🐢 🟠 🐢 🟣
It already works:
{% for turtle in turtles %}
🐢 {{ loop.cycle('🔵', '🔴', '🟠', '🟣') }}
{% endfor %}
With loop. yep ! And i really like this DX :)
Maybe this is something to highlight in the doc ? Or even deprecate the cycle function ?
With
loop.yep ! And i really like this DX :)Maybe this is something to highlight in the doc ? Or even deprecate the cycle function ?
I think both serve different purposes. I forgot to say that this is available as of 4.0. Docs are available: https://github.com/twigphp/Twig/blob/4.x/doc/tags/for.rst
Thank you @smnandre.