Twig icon indicating copy to clipboard operation
Twig copied to clipboard

Adjust `cycle` implementation

Open smnandre opened this issue 1 year ago • 1 comments

Update code following #4158

  • return mixed
  • trigger when non countable
  • type the position argument

Add doc precisions

smnandre avatar Aug 26 '24 23:08 smnandre

~~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 avatar Aug 27 '24 06:08 smnandre

@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)

stof avatar Aug 29 '24 15:08 stof

@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)

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 avatar Aug 30 '24 17:08 smnandre

@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)

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 %}

fabpot avatar Aug 30 '24 17:08 fabpot

With loop. yep ! And i really like this DX :)

Maybe this is something to highlight in the doc ? Or even deprecate the cycle function ?

smnandre avatar Aug 30 '24 17:08 smnandre

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

fabpot avatar Aug 30 '24 17:08 fabpot

Thank you @smnandre.

fabpot avatar Aug 30 '24 18:08 fabpot