Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment a variable in django templates

All,

How Can we increment a value like the following in django templates,

  {{ flag =0 }}

  {% for op in options %}
   {{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/>
  {% endfor %}

thanks..

like image 369
Hulk Avatar asked Mar 24 '10 11:03

Hulk


2 Answers

You explicitly can't do that in a template. Variable assignment is not allowed.

However if all you want is a counter in your loop, you just need to use {{ forloop.counter }}.

like image 200
Daniel Roseman Avatar answered Nov 04 '22 01:11

Daniel Roseman


I don't think it's intended you should alter data in your templates. For in your specific case, you could instead use the forloop.counter variable.

For example:

{% for op in options %}
  {{op.choices}}<input type="radio" name="template" id="template{{forloop.counter}}" value="template{{forloop.counter}}"/>
{% endfor %}

Also note that I added that number to the id attributes of the <input /> tag. Otherwise you'll have multiple inputs with the same id.

EDIT: I didn't note that it was a radio input. You could of course have the same name for each <input type="radio" />.

like image 20
mojbro Avatar answered Nov 04 '22 01:11

mojbro