Forloop

Forloop

Forloop

Name Type Description
name String The name of the current forloop (automatically generated from the for tag's variable and collection names).
length Number The number of items in the forloop
index Number The 1-based index of the current item in the for loop.
index0 Number The 0-based index of the current item in the for loop.
rindex Number The 1-based index of the current item in the for loop counting from the end to the beginning (the reverse of index).
rindex0 Number The 0-based index of the current item in the for loop counting from the end to the beginning (the reverse of index0).
first Boolean True if the current item is the first item in the for loop.
last Boolean True if the current item is the last item in the for loop.

{% for %}

Iterates through every item in a list. Executes and outputs a block of code to the template for each item in the list.

Examples

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

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

Looping collection and accessing forloop properties

Copy
{% for item in collection %}
Item {{forloop.index}} out of {{forloop.length}}
{{ item }}
{{forloop.rindex0}} items remaining
{% endfor %}

Loop Request Headers

Copy
{% for header in request.headers %} {{ header }}: {{ request.headers[header] }} {% endfor %}

Looping Request Headers with Key

Copy
{% for key in request.headers.keys %} {{ key }}: {{ request.headers[key] }} {% endfor %}

Loop Post Parameters

Copy

Post Parameters

{% for param in request.post_params %}
{{param}}
{% if request.post_params.by_name[param] is_list %}
    {% for value in request.post_params.by_name[param] %}
  • {{ value }}
  • {% endfor %}
{% else %} {{ request.post_params.by_name[param] }} {% endif %}
{% endfor %}

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 %}

List all custom properties for the current user

Copy

User Properties:

    {% for property in user %} --equivalent to {% for property in user.properties %}
  • {{property}} = {{ user[property] }}
  • {% endfor %}

List all keys and values for a labels field

Copy
    {% for kvp in entity.labels %}
  • {{kvp.Key}} = {{kvp.Value}}
  • {% endfor %}