Looping

Using a for block, you can iterate anything that implements IEnumerable.

{% assign children = "Alec,Gabrielle,Isabella" | split:"," %}

{% for child in children %}
* {{ child }}
{% endfor %}
* Alec

* Gabrielle

* Isabella

(See Whitespace Control to learn why there are extra line breaks.)

Within a loop, you have access to a special object called forloop. It provides the following properties, which are set on each iteration.

  • forloop.index: The index of the loop, starting at 1
  • forloop.index0: The index of the loop, starting at 0
  • forloop.rindex: The reverse index of the loop, ending at 0
  • forloop.rindex0: The reverse index of the loop, ending at 1 (yes, this seems weird to me too…)
  • forloop.first: Returns true if this is the first iteration
  • forloop.last: Returns true if this is the last iteration
  • forloop.length: The total number of loops to be performed

Example: deciding whether or not to show a comma.

{% for child in children %}
{{ child }}{% unless forloop.last %}, {% endunless %}
{% endfor %}
Alec,

Gabrielle,

Isabella

(If you think you’ll need to form so-called “Oxford Lists” often, there’s a custom filter example for it in the chapter on Custom Filters).

Tags for break and continue work as expected inside loops. Note that these are tags not blocks, so they do not close.

An else tag within a loop will display content if the collection is empty.

{% for child in children %}
  * {{ child }}
{% else %}
  You have no kids. Enjoy all your money.
{% endfor %}