for
The for tag loops over items in a sequence (array or hash).
For example, to loop over a list of blog posts you could do the following:
The "post" value will hold each value in the posts array as it's looped through.
The loop variable
Inside of a for loop block you have access to some special variables. These variables are not accessible outside of the for loop.
The loop variable holds an array of values.
Iterate over a sequence of numbers or letters.
If you need to iterate over a sequence of numbers you can use the .. operator.
The above will output all numbers from 0 to 10 with each on a new line.
You can do a similar thing with letters.
Variable | Description |
---|---|
loop.index |
The current iteration of the loop starting at 1. {{ loop.index }} |
loop.index0 |
The current iteration of the loop starting at 0. {{ loop.index0 }} |
loop.revindex |
The number of iterations from the end of the loop starting at 1. {{ loop.revindex }} |
loop.revindex0 |
The number of iterations from the end of the loop starting at 0. {{ loop.revindex0 }} |
loop.first |
Holds whether or not the current iteration is the first iteration. True if it's the first iteration, false if it's not. {% if loop.first %} |
loop.last |
Holds whether or not the current iteration is the last iteration. True if it's the last iteration, false if it's not. {% if loop.last %} |
loop.length |
Holds the number of items in the loop sequence. {{ loop.length }} |
loop.parent |
Holds the parent context; the variable being looped through. {% for post in posts %} In the above code loop.parent would hold the posts value. |
The loop.length, loop.revindex, loop.revindex0 and loop.last variables are not available when looping with a condition.
Adding a loop condition
You cannot force breaking out of a loop, however, you can add a condition that allows you to skip items in the loop.
The following would skip all users which are not active.
Note, do not use the loop variable within the condition. For example, adding a condition like the following won't work as the index is only incremented when the condition is true. In this case the condition will never match.
The else clause
If no looping will occur because the sequence is empty, then you can output a replacement by using else.
Iterating over keys
By default, the for loop will only iterate over the values of the sequence. You can use the keys filter to iterate over only the array keys.
Iterating over both keys and values
Below is how you would iterate over both the keys and values of an array.
Iterate over a subset
If you wanted to iterate over a portion of the array then you can achieve this with the slice filter.