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

58,236

Solution 1

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

{{ forloop.last }}

Share:
58,236

Related videos on Youtube

Daniel Kivatinos
Author by

Daniel Kivatinos

I'm the COO and co-founder of drchrono. drchrono is an electronic medical records platform for physicians and patients. Looking to change the world through hacking and technology? We are hiring at drchrono. drchrono.com/careers Take our hacker challenge Learn more here about our hackathons - iOS Engineer Django Engineer If you're also interested in leveraging an API in healthcare, you can learn more here - drchrono.com/api

Updated on July 08, 2022

Comments

  • Daniel Kivatinos
    Daniel Kivatinos almost 2 years

    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?

  • Tagar
    Tagar about 7 years
    If there are nested loops, will it check the inner-most loop?
  • Tagar
    Tagar about 7 years
    Is this a feature of a newer Jinja version? Getting "rendering template: 'forloop' is undefined" on {% if not(forloop.last) %} , {% endif %}
  • ndmeiri
    ndmeiri over 6 years
    If there are nested loops, use forloop.parentloop to access the loop surrounding the current one. So to check for the last iteration of a parent loop, one could use forloop.parentloop.last. See the documentation. @Tagar
  • ndmeiri
    ndmeiri over 6 years
    So, in short, forloop.last will check for the last iteration of the inner-most loop.