twig for each code example

Example 1: twig foreach

{% for key, value in array %}
  {{ key }}: {{ value }}
{% endfor %}

Example 2: foreach twig

{% for user in users %}
        <li>{{ user.username|e }}</li>
    {% endfor %}

Example 3: twig loop

loop.index	    The current iteration of the loop. (1 indexed)
loop.index0	    The current iteration of the loop. (0 indexed)
loop.revindex	The number of iterations from the end of the loop (1 indexed)
loop.revindex0	The number of iterations from the end of the loop (0 indexed)
loop.first	    True if first iteration
loop.last	    True if last iteration
loop.length	    The number of items in the sequence
loop.parent	    The parent context

{% for user in users %}
    {{ loop.index }} - {{ user.username }}
{% endfor %}

Example 4: twig for

<ul>
    {% for key, user in users %}
        <li>{{ key }}: {{ user.username|e }}</li>
    {% endfor %}
</ul>

Example 5: twig loop variables

{% for user in users %}
    {{ loop.index }} - {{ user.username }}
{% endfor %}

Example 6: how to for loop twig

{% for letter in 'a'..'z' %}
    * {{ letter }}
{% endfor %}

Tags:

Php Example