Sathiyakugan
Sathiyakugan

Reputation: 684

Declare variables and increase that inside Django templates

I want to declare a variables inside Django templates and increase that by one .

my code is

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

It's giving the error of

jinja2.exceptions.TemplateSyntaxError: can't assign to 'const'

How to declare the variable and increase it?

Upvotes: 0

Views: 667

Answers (1)

Iakovos Belonias
Iakovos Belonias

Reputation: 1373

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

Also keep in mind

{{ forloop.first }} {# True if this is the first time through the loop #}

and

{{ forloop.last }}  {# True if this is the last time through the loop #}

Upvotes: 2

Related Questions