python 在 Django 模板中增加一个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2507284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
increment a variable in django templates
提问by Hulk
All,
全部,
How Can we increment a value like the following in django templates,
我们如何在 Django 模板中增加如下所示的值,
{{ flag =0 }}
{% for op in options %}
{{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/>
{% endfor %}
thanks..
谢谢..
回答by mojbro
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.
我不认为您应该更改模板中的数据。对于您的特定情况,您可以改为使用forloop.counter
变量。
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.
另请注意,我将该数字添加到标签的id
属性中<input />
。否则,您将有多个具有相同 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" />
.
编辑:我没有注意到这是一个无线电输入。您当然可以为每个<input type="radio" />
.
回答by Daniel Roseman
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 }}
.
但是,如果您只想要循环中的计数器,则只需使用{{ forloop.counter }}
.