v1.9.1
Iteration tags run blocks of code repeatedly.
Basic Usage
for…in
Repeatedly executes a block of code. For a full list of attributes available within a for loop, see forloop.
Input
{% for product in collection.products %} |
Output
hat shirt pants |
For loops can iterate over arrays, hashes, and ranges of integers.
When iterating a hash, item[0] contains the key, and item[1] contains the value:
Input
{% for item in hash %} |
Output
* key1: value1 |
else
Specifies a fallback case for a for loop which will run if the loop has zero length.
Input
{% for product in collection.products %} |
Output
The collection is empty. |
break
Causes the loop to stop iterating when it encounters the break tag.
Input
{% for i in (1..5) %} |
Output
1 2 3 |
continue
Causes the loop to skip the current iteration when it encounters the continue tag.
Input
{% for i in (1..5) %} |
Output
1 2 3 5 |
forloop
There’s a forloop object available inside for loops. It’s used to indicate the current state of for loop.
The forloop.first, forloop.last and forloop.length property:
Input
{% for i in (1..5) %} |
Output
First |
The forloop.index, forloop.index0, forloop.rindex and forloop.rindex0 property:
Input
index index0 rindex rindex0 |
Output
index index0 rindex rindex0 |
Parameters
limit
Limits the loop to the specified number of iterations.
Input
<!-- if array = [1,2,3,4,5,6] --> |
Output
1 2 |
offset
Begins the loop at the specified index.
Input
<!-- if array = [1,2,3,4,5,6] --> |
Output
3 4 5 6 |
range
Defines a range of numbers to loop through. The range can be defined by both literal and variable numbers.
Input
{% for i in (3..5) %} |
Output
3 4 5 |
reversed
Reverses the order of the loop. Note that this flag’s spelling is different from the filter reverse.
Input
<!-- if array = [1,2,3,4,5,6] --> |
Output
6 5 4 3 2 1 |
When used with additional parameters, order is important. Leading with reversed reverses the order of the loop before executing the other parameters.
Input
{% for i in (1..8) reversed limit: 4 %} |
Output
8 7 6 5 |
Input
{% for i in (1..8) limit: 4 reversed %} |
Output
4 3 2 1 |