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

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

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