【问题标题】:Declare variables and increase that inside Django templates声明变量并在 Django 模板中增加变量
【发布时间】:2019-08-07 05:07:15
【问题描述】:

我想在 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'

如何声明变量并增加变量?

【问题讨论】:

  • 你应该使用forloop.counter,它支持0和1的起始索引。

标签: python django


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-06-02
    • 2010-10-17
    • 2016-04-15
    • 1970-01-01
    • 2017-06-27
    • 2011-01-31
    • 2019-06-08
    • 2012-01-29
    • 1970-01-01
    相关资源
    最近更新 更多