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.

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 %}