{% for %}

The {% for %} tag repeatedly executes a block of code for every item in a list or collection.

Syntax

{% for itemname in collection [offset: number] [limit: number] [reversed] %}...{% endfor %}

collection: May be any array, list, or collection. May alternatively be a range, which is defined using the syntax: "(start..end)". Eg: (1..5) or (1..page.num_items.value).

offset: Starts the for loop at a specific index. Alternatively, if the for loop is included multiple times in the template, use the keyword "continue" to continue iteration from where it previously left off.

limit: Exits the for loop at a specific index.

reversed: Reverses the order of the loop.

The for tag creates a new child scope.

Additionally, inside a forloop, there are several related tags and properties that you can use to control output.

The properties indicating the current status of the forloop are saved on the {{ forloop }} object.

Additional tags that can be used inside a forloop are:

{% cycle %}: Loops through a group of strings and outputs them in the order that they were passed as parameters. Each time cycle is called, the next string that was passed as a parameter is output. For more details read the full cycle documentation.

{% break %}: Causes the loop to stop iterating when it encounters the break tag.

{% continue %}: Causes the loop to skip the current iteration when it encounters the continue tag.

Examples

To map a collection of entities into a human-readable list of titles linking to the entities:

Copy
{% for entity in collection.items -%} {{ entity.linked_title }}{% unless forloop.first -%}{% if forloop.length == 2 %} and {% else %}, {% if forloop.last %}and {% endif %}{% endif %}{% endunless %} {%- endfor %}

For loop reversed

Copy
Template:{% for number in (1..10) reversed -%} {%- if number == 9 %}{% continue %}{% endif -%} {%- if number == 6 %}{% break %}{% endif -%} {{number}} {%- endfor %} Output: 1087

For loop with limit

Copy
Template: {% assign collection = (1..6) %} First Three: {% for item in collection limit:3 -%} {{item}} {%- endfor %} The Rest: {% for item in collection offset:continue -%} {{item}} {%- endfor %} Output: First Three: 123 The Rest: 456