Iteration tags
Iteration tags repeatedly run blocks of code.
for
Repeatedly executes a block of code. For a full list of attributes available within a for
loop, see forloop (object).
for
loops can output a maximum of 50 results per page. In cases where there are more than 50 results, use the paginate tag to split them across multiple pages.
{% for product in collection.products %}
{{ product.title }}
{% endfor %}
Fancy hat Snazzy shirt Dapper pants
else
Specifies a fallback case for a for
loop which will run if the loop has zero length (for example, you loop over a collection that has no products):
{% for product in collection.products %}
{{ product.title }}
{% else %}
The collection is empty.
{% endfor %}
The collection is empty.
break
Causes the loop to stop iterating when it encounters the break
tag.
{% for i in (1..5) %}
{% if i == 4 %}
{% break %}
{% else %}
{{ i }}
{% endif %}
{% endfor %}
1 2 3
continue
Causes the loop to skip the current iteration when it encounters the continue
tag.
{% for i in (1..5) %}
{% if i == 4 %}
{% continue %}
{% else %}
{{ i }}
{% endif %}
{% endfor %}
1 2 3 5
for tag parameters
limit
Exits the for loop at a specific index.
<!-- numbers = [1,2,3,4,5] -->
{% for item in numbers limit:2 %}
{{ item }}
{% endfor %}
1 2
offset
Starts the for loop at a specific index.
<!-- numbers = [1,2,3,4,5] -->
{% for item in numbers offset:2 %}
{{ item }}
{% endfor %}
3 4 5
range
Defines a range of numbers to loop through. You can define the range using both literal and variable values.
{% for i in (3..5) %}
{{ i }}
{% endfor %}
{% assign my_limit = 4 %}
{% for i in (1..my_limit) %}
{{ i }}
{% endfor %}
3 4 5
1 2 3 4
reversed
Reverses the order of the loop.
<!-- if array = [1,2,3,4,5,6] -->
{% for item in array reversed %}
{{ item }}
{% endfor %}
6 5 4 3 2 1
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.
cycle
must be used within a for loop block.
{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}
one
two
three
one
Uses for cycle
include:
- applying odd/even classes to rows in a table
- applying a unique class to the last product thumbnail in a row
Updated about 3 years ago