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
Top comments (2)
Interesting, I have never seen a Django template before. If there are nested loops is there a way to distinguish between inner and outer for loops. This magical for loop variable seems a bit mysterious to me. I have never really reached for a template language and mostly stuck with the built-in string Template for my very limited use of templates.
Sorry for the late reply.
For two loops, it seems like there is the forloop.parentloop .
e.g. forloop.parentloop.counter
However for three or more loops I do not know yet whether there is a way to distinguish each of them.
This stackoverflow might be of a help: stackoverflow.com/questions/237651...