Daniel Kivatinos
Daniel Kivatinos

Reputation: 25046

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

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?

Upvotes: 134

Views: 70531

Answers (3)

black
black

Reputation: 857

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 a list with three items:

first_item, second_item, third_item

Upvotes: 3

fuentesjr
fuentesjr

Reputation: 52348

{{ forloop.last }}

Upvotes: 14

Paolo Bergantino
Paolo Bergantino

Reputation: 488594

You would use forloop.last. For example:

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

Upvotes: 285

Related Questions