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 }}
Related videos on Youtube
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, 2022Comments
-
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 about 7 yearsIf there are nested loops, will it check the inner-most loop?
-
Tagar about 7 yearsIs this a feature of a newer Jinja version? Getting "rendering template: 'forloop' is undefined" on {% if not(forloop.last) %} , {% endif %}
-
ndmeiri over 6 yearsIf 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 useforloop.parentloop.last
. See the documentation. @Tagar -
ndmeiri over 6 yearsSo, in short,
forloop.last
will check for the last iteration of the inner-most loop.