How to check for first or last iteration of a for loop in a Django template


Django tip:

You can use forloop.first or forloop.last to check if the current iteration is the first or the last time through a for loop in your Django templates like so:

{% for item in item_list %}
    {{ forloop.first }}  # True if this is the first time through the loop
    {{ forloop.last }}   # True if this is the last time through the loop
{% endfor %}