Объявите переменные и увеличьте их внутри шаблонов Django - PullRequest
0 голосов
/ 16 марта 2019

Я хочу объявить переменные внутри шаблонов 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'

Как объявить переменную и увеличить ее?

1 Ответ

2 голосов
/ 16 марта 2019

То, что вы хотите, это

{% 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 #}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...