twig Basic template syntax For Loop

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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: https://twigfiddle.com/mxwkea/2

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 %}
    {{ currentObject.name }}
{% endfor %}

See this working with JSON data: https://twigfiddle.com/mxwkea



Got any twig Question?