This article introduces how to use the Twig for loop and provides simple examples.
HOW TO USE THE FOR LOOP IN TWIG
{# 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 repeat a series of processes a certain number of times, write it 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>{% 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 expressions within the loop. The example above displays uppercase letters from A to Z.
EXAMPLES OF USING THE FOR LOOP IN TWIG
Getting the index
While we specify 'i' when iterating a fixed number of times, you can also get the index 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 current loop iteration count. If you want to start from "0", use loop.index0.
Checking for the first (or last) loop iteration
{% set users = ['foo', 'bar', 'baz'] %}
{# use loop.first #}
{% for user in users %}
{% if loop.first %}
{{ user }}
{% endif %}
{% endfor %}
{# result #}
fooThe example above checks for the first iteration of the loop. For the last iteration, use loop.last.
You can also use loop.length, loop.revindex, loop.revindex0, loop.parent, and more.
Using with added 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
bazIn the example above, a condition is added to display only the names of active users.
Getting both Key and Value from an 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: bazI remember how difficult it was for me to understand concepts like arrays, for loops, and foreach when I started learning programming, especially since I originally disliked math and had a humanities background. That's why I tried to explain it a bit more carefully here.
I will add more examples when I encounter new use cases.
RECOMMENDED TWIG BOOKS
I haven't read any books specifically dedicated to Twig, but I found one on Amazon Kindle.
📦