CASE: how to use {% if forloop.first %} and/or {% if forloop.last %}

Got a question the other day, why we often use {% if forloop.first %} and / or {% if forloop.last %} in our account-templates.

We use this, if we don’t want to display a certain loop. For instance, if we have an overview of all the costs, and at the end of this overview we want to make a TOTAL of these costs.
But this TOTAL can’t be displayed, if we don’t have any costs. If you don’t use a forloop.last, that line with the TOTAL will always be displayed. And we don’t want that.

Let’s have a deeper look:

  1. Select the accounts you want, here: {% input period.custom.overzicht.kosten as:account_collection range:6 accounts_var:kosten %}
{% for kost in kosten %}{% if forloop.first %}
|     Number                |       Name            |       Value           |
|---------20%---------------|---------45%-----------|----------------------:+{% endif %}
| {{ kost.number }}         | {{ kost.name }}       | {%=$1+ kost.value | currency %}{% if forloop.last %}
|                           |                       | **{{ $1 | currency }}**{% endif %}{% endfor %}

The code between {% if forloop.first %} and {% endif %} will be run for every loop, but it will only be displayed by the first loop.
So, if you have 6 accounts in our collection “kosten”, the code will only be displayed by the first loop. Iy you don’t have any account in the collection, the code won’t be run because there are no loops at all.

Same thing goes for the {% if forloop.last %}: the code between {% if forloop.last %} and {% endif %} will be done for every loop, but only at the last loop will it be printed.
If there are no loops (the collection is empty), nothing will be printed.

If you don’t use forloop.first and forloop.last, our header (Number, Name, Value) and total will always be displayed, even if our collection “kosten” is empty.

4 Likes