Reishi Mitani
Posted on August 3, 2020
Environment
python 3.6.5
django 2.1
===============
Enumerating in a Django Template
I recently had a problem where I had to enumerate through a list passed from the view to the template. You can use these methods below.
variable | definition |
---|---|
forloop.counter |
enumerating, index starting from 1 |
forloop.counter0 |
enumerating, index starting from 0 |
forloop.revcounter |
enumerating, index starting from the tail |
forloop.revcounter0 |
enumerating, index starting from 0 |
forloop.first |
true when index is at 0 |
forloop.last |
true when index is at tail |
forloop.parentloop |
enumerates through the parent loop |
An example of the forloop.counter
will be:
{% for person in listlike_var %}
{{ forloop.counter }} : {{ person.name }}
{% endfor %}
Output:
1: sally
2: bob
3: john
For forloop.counter0
it will be:
{% for person in listlike_var %}
{{ forloop.counter0 }} : {{ person.name }}
{% endfor %}
0: sally
1: bob
2: john
As for the length of a list, listlike_var|length
can be used.
{{ listlike_var|length }}
3
💖 💪 🙅 🚩
Reishi Mitani
Posted on August 3, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.