For Loops
Liquid allows for loops over arrays or collections of data. Loop over children, labels, blog posts, or navigation elements easily.
{% for child in item.children %}
<h2>{{ child.title }}</h2>
{{ child.data.excerpt }}
{% endfor %}
During every for loop the following helper variables are available for extra data and display needs:
Key | Description |
---|---|
forloop.length | length of the entire for loop |
forloop.index | index of the current iteration |
forloop.index0 | index of the current iteration (zero based) |
forloop.rindex | how many items are still left? |
forloop.rindex0 | how many items are still left? (zero based) |
forloop.first | is this the first iteration? |
forloop.last | is this the last iteration? |
There are several attributes you can use to influence which items you receive in your loop. limit
lets you restrict how many times the loop runs, and offset
lets you skip the given number of items at the beginning of the collection.
# array = [1,2,3,4,5,6]
{% for item in array limit:2 offset:2 %}
{{ item }}
{% endfor %}
# => 34
Instead of looping over an existing collection, you can define a range of numbers to loop through. The range can be defined by both literal and variable numbers:
# if item.quantity is 4...
{% for i in (1..item.quantity) %}
{{ i }}
{% endfor %}
# => 1234