How do I check for last loop iteration in Django template?

Daniel Kivatinos picture Daniel Kivatinos · May 7, 2009 · Viewed 50.2k times · Source

I have a basic question, in the Django template language how can you tell if you are at the last loop iteration in a for loop?

Answer

Paolo Bergantino picture Paolo Bergantino · May 7, 2009

You would use forloop.last. For example:

<ul>
{% for item in menu_items %}
    <li{% if forloop.last %} class='last'{% endif %}>{{ item }}</li>
{% endfor %}
</ul>