声明变量并在Django模板中增加它

2024-04-26 14:55:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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: can't assign to 'const'

如何声明变量并增加它?你知道吗


Tags: djangoin模板声明密码foraddressmy
1条回答
网友
1楼 · 发布于 2024-04-26 14:55:41

What you want is

{% 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 #}

相关问题 更多 >