{% 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:    
{% 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 %}
Template:{% for number in (1..10) reversed -%}
    {%- if number == 9 %}{% continue %}{% endif -%}
    {%- if number == 6 %}{% break %}{% endif -%}
    <span class="{% cycle 'even', 'odd' %}">{{number}}</span>
{%- endfor %}
Output: <span class="even">10</span><span class="odd">8</span><span class="even">7</span>
Template: {% assign collection = (1..6) %}
First Three: {% for item in collection limit:3 -%}
    <span class="{% if forloop.first %}first{% elsif forloop.last %}last{% endif %}">{{item}}</span>
{%- endfor %}
The Rest: {% for item in collection offset:continue -%}
    <span class="{% if forloop.first %}first{% elsif forloop.last %}last{% endif %}">{{item}}</span>
{%- endfor %}
Output: First Three: <span class="first">1</span><span class="">2</span><span class="last">3</span>
The Rest: <span class="first">4</span><span class="">5</span><span class="last">6</span>

Developer Overview

Liquid Markup