twig Basic template syntax For Loop


For loops can be really useful in TWIG, allowing the creation of data-dynamic web pages.

Say we create a simple array of numbers:

{% set array = "3,1,2" %}

We can then iterate over the array and print out whatever we want. Any data within the array block will be outputted in relation to the amount of data within the array. This example would print out three h1 elements with the array data concatenated.

{% for current in array %}
    <h1>This is number {{ current }} in the array </h1>
{% endear %}

Note that {{ current }} was used to access the data and not a version of array

See this working:

A further example of this could be using objects. For example, say we have an Entity object with the field 'name' along with its relevant getters and setters. If a number of these entities are also stored within the Array, they can be accessed like any other Objects within TWIG:

{% for currentObject in ArrayOfObjects %}
    {{ }}
{% endfor %}

See this working with JSON data: