Example of basic looping through array values in Symfony Twig

Cycle through an array of values for current year and 5 years into the future:

{% set start_yr = date() | date('Y') %}
{% set end_yr = start_yr + 5 %}
{% for yr in start_yr..end_yr %}
    {{ cycle(['odd', 'even'], loop.index0) }}
{% endfor %}

The array “colors” would probably be better off defined in the controller then passed into the view here, but here’s an example of how to set and initialize a new array in Twig. This can be handy if you are setting certain display options in the view that’s not tied to any data or logic that would be used anywhere but inside your views.

{% set colors= ['red', 'orange', 'blue'] %}
{% for i in 0..10 %}
    {{ cycle(colors, i) }}
{% endfor %}

Aaron Belchamber has written 247 articles

Leave a Reply

Your email address will not be published. Required fields are marked *