increment a variable in django templates

纵饮孤独 提交于 2019-12-20 19:05:14

问题


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..


回答1:


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" />.




回答2:


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 }}.




回答3:


You might also want to look into having Django forms produce these values



来源:https://stackoverflow.com/questions/2507284/increment-a-variable-in-django-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!