Skip to content

For loops

harrydeluxe edited this page May 13, 2012 · 1 revision

Liquid allows for loops over collections:

{% for item in array %} 
  {{ item }}
{% endfor %} 

During every for loop, the following helper variables are available for extra styling needs:

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 iternation? 

There are several attributes you can use to influence which items you receive in your loop

limit:int lets you restrict how many items you get. offset:int lets you start the collection with the nth item.

# array = [1,2,3,4,5,6]
{% for item in array limit:2 offset:2 %} 
  {{ item }}
{% endfor %} 
# results in 3,4 

Reversing the loop

{% for item in collection reversed %} {{item}} {% endfor %}

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 %}
# results in 1,2,3,4
Clone this wiki locally