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

DjangoFor LoopDjango Templates

Django Problem Overview


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?

Django Solutions


Solution 1 - Django

You would use forloop.last. For example:

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

Solution 2 - Django

{{ forloop.last }}

Solution 3 - Django

You can basically use this logic in a for loop:

{% if forloop.last %}
   # Do something here
{% endif %}

For example, if you need to put a comma after each item except for the last one, you can use this snippet:

  {% for item in item_list %}
    {% if forloop.last %}
        {{ item }}
    {% else %}
         {{ item }},
    {% endif %}
  {% endfor %}

which will become for a list with three items:

first_item, second_item, third_item

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel KivatinosView Question on Stackoverflow
Solution 1 - DjangoPaolo BergantinoView Answer on Stackoverflow
Solution 2 - DjangofuentesjrView Answer on Stackoverflow
Solution 3 - DjangoblackView Answer on Stackoverflow