Iteration and lists
Looping with for
When you have a collection of items, you often want to loop over it and display a bullet list or an ordered list. This is what for
is made… for.
Let’s define a list in our sample data tab:
{
"fruits": [
"Apple",
"Banana",
"Lemon"
]
}
We can now display this list in our template:
<ul>
{% for fruit in fruits %}
<li>{{fruit}}</li>
{% endfor %}
</ul>
Nested data
We can even use nested data in a for loop. If we define the following data:
{
"invoiceItems": [
{ "product": "delicious waffle", "quantity": 42 },
{ "product": "magic brownie", "quantity": 24 }
]
}
Then our template can reference the information of each item:
<ul>
{% for item in invoiceItems %}
<li>{{item.quantity}} {{item.product}}</li>
{% endfor %}
</ul>
Empty collections
If you want to handle an empty collection in a specific way, you can use the else
keyword:
{% for specialTerm in contract.specialTerms %}
<p>{{specialTerm}}</p>
{% else %}
<p>No specific terms.</p>
{% endfor %}
Advanced iteration
Liquid provides a lot of useful constructs to traverse collections. You can build tables, use ranges, reverse the collection or use limit and offsets.
To learn more read the Liquid documentation on iteration.