Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run this code in django template

this is my code :

{% for i,j in enumerate(a) %}
    {{i}} ,{{j}}
{% endfor%}

but , it show a error , i think it cant run the enumerate method ,

so how to run the enumerate in django template ,

thanks

like image 561
zjm1126 Avatar asked Feb 16 '11 06:02

zjm1126


People also ask

How do I run a Django template?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

What does {{ name }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.


2 Answers

The template subsystem has some special constructs built into the for/endfor block that allows you to access the current index of the loop without having to call enumerate.

{% for j in a %}
    {{ forloop.counter0 }}, {{ j }}
{% endfor %}

While this snippet solves your immediate problem, if you're expecting to have access to Python builtins and other Python constructs inside your Django templates, you may be misunderstanding the sandbox that it provides/enforces.

like image 96
Joe Holloway Avatar answered Oct 09 '22 04:10

Joe Holloway


you can use {{ forloop.counter }} or {{ forloop.counter0 }} for the same effect, the latter is 0-indexed, thus more like enumerate.

like image 17
Uku Loskit Avatar answered Oct 09 '22 04:10

Uku Loskit