Iteration (dealing with lists)
Looping over lists is a very frequent need and in this guide we'll go over the various ways you can do it.
Here are the essential aspects of iteration but you can learn more in the official documentation.
The simplest loop
Let's use the data we defined in an earlier section:
{
"orderId": 1234,
"orderStatus": "pending",
"invoiceId": null,
"client": {
"civility": "Mr",
"fullName": "Peter Parker",
"isNewClient": true
},
"lineItems": [
{ "product": "Super strong silk", "quantity": 100, "price": 123.45 },
{ "product": "Electronic components", "quantity": 12, "price": 12.34 }
]
}
We can loop over the lineItems
array to list our products using a for
loop. It will repeat the code for each item in the array:
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total</th>
</tr>
{% for item in lineItems %}
<tr>
<td>{{item.product}}</td>
<td>{{item.quantity}}</td>
<td>${{item.price | with_delimiter, precision: 2}}</td>
<td>${{item.price | times: item.quantity | with_delimiter, precision: 2}}</td>
</tr>
{% endfor %}
</table>
The resulting HTML will look like this:
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total</th>
</tr>
<tr>
<td>Super strong silk<td>
<td>100</td>
<td>$123.45</td>
<td>$12,345.00</td>
</tr>
<tr>
<td>Electronic components</td>
<td>12</td>
<td>$12.34</td>
<td>$148.08</td>
</tr>
</table>
Related links
The forloop object
Inside a for
loop, you get access to a special object that stores the current state of the loop. It can be useful to build special cases for the first or last iteration, for instance.
{% for item in lineItems %}
{% if forloop.first == true %}
<p>{{item.product}} is the first item.</p>
{% elsif forloop.last == true %}
<p>{{item.product}} is the last item.</p>
{% else %}
<p>{{item.product}} is an item.</p>
{% endif %}
{% endfor %}
Last updated
Was this helpful?