I would like to introduce how to use the for statement of Twig and a simple example.
I think that the loop statement by for has many uses.
Official:for – Documentation
How to use for statement in Twig
I will summarize the basic usage.
{# sample array #} {% set users = ['foo', 'bar'] %} <ul> {% for user in users %} <li>{{ user }}</li> {% endfor %} </ul> {# result #} <ul> <li>foo</li> <li>bar</li> </ul>
If you want to iterate a certain number of series of processes, write as follows.
{# use the .. operator #} {% for i in 0..5 %} * {{ i }}<br> {% endfor %} {# result #} * 0<br> * 1<br> * 2<br> * 3<br> * 4<br> * 5<br>
Not only numbers but also letters such as alphabets are possible.
{% for letter in 'a'..'c' %} * {{ letter }}<br> {% endfor %} {# result #} * a<br> * b<br> * c<br> {# can use any expression #} {% for letter in 'a'|upper..'z'|upper %} * {{ letter }} {% endfor %}
You can also use Twig’s expression
in your expressions. In the above example, uppercase letters A to Z are displayed.It is also possible to give only one side.
Example of using for statement in Twig
Get index
When using a certain number of times, i
is specified, but index can be obtained in other cases.
{# use loop.index (1 indexed) #} {% set users = ['foo', 'bar'] %} <ul> {% for user in users %} <li>{{ loop.index }}-{{ user }}</li> {% endfor %} </ul> {# result #} <ul> <li>1-foo</li> <li>2-bar</li> </ul>
You can get the iteration of the current loop. If you want to start from “0”, use loop.index0
.
Determine the beginning (end) of the loop
{% set users = ['foo', 'bar', 'baz'] %} {# use loop.first #} {% for user in users %} {% if loop.first %} {{ user }} {% endif %} {% endfor %} {# result #} foo
The above example determines the first loop. For the last case, use loop.last
.
Loop is other You can use loop.length, loop.revindex, loop.revindex0, loop.parent
, etc.
Use by adding conditions
{% set users = [ { 'name': 'foo', 'active': true }, { 'name': 'bar', 'active': false }, { 'name': 'baz', 'active': true } ] %} {% for user in users if user.active %} {{ user.name }}<br> {% endfor %} {# result #} foo baz
In the above example, the condition is added so that only the active user name is displayed.
Get both KEY and Value from the array
{% set users = [ { 'name': 'foo', 'active': true }, { 'name': 'bar', 'active': false }, { 'name': 'baz', 'active': true } ] %} {% for key, user in users %} {{ key }}: {{ user.name }}<br> {% endfor %} {# result #} 0: foo 1: bar 2: baz
If you want to get the Key and Value, it will be above.
Originally I hated mathematics and was a liberal arts student, but when I started studying programs, I remember it was very difficult to understand arrays, for loops, and foreach. So I tried to explain it a little carefully.
Also, I will add it when I use it as a sample.