我想在Django模板中声明一个变量,并将其增加一个。
我的代码是
{% with 0 as my_variable %}
{% for address in user.addresses %}
{{my_variable=my_variable+1}}
{% if my_variable==1 %}
// do something
{% else %}
// do something
{% endif %}
{% endfor %}
{% endwith %}
出现错误
jinja2.exceptions.TemplateSyntaxError:无法分配给'const'
如何声明变量并增加变量?
答案 0 :(得分:2)
{% for item in item_list %}
{{ forloop.counter }} {# starting index 1 #}
{{ forloop.counter0 }} {# starting index 0 #}
{# do your stuff #}
{% endfor %}
{{ forloop.counter }} {# The current iteration of the loop (1-indexed) #}
{{ forloop.counter0 }} {# The current iteration of the loop (0-indexed) #}
还请记住
{{ forloop.first }} {# True if this is the first time through the loop #}
和
{{ forloop.last }} {# True if this is the last time through the loop #}