3

Following is the code where I need to update a variable.

{% with a=1 %}
{% for x in object_list %}
    {% if 'clone' in x.game and a is 1 %}
        <div class="alert alert-primary">
            <h2 class="p-3">{{ x.title }}</h2>
        </div>
        {{ a=2 }} # here is where I update it
    {% endif %}
{% endfor %}
{% endwith %}

but instead of {{ a=2 }} setting a to 2, it throws the following error:

TemplateSyntaxError at /
Could not parse the remainder: '=2' from 'a=2'
karel
  • 5,489
  • 46
  • 45
  • 50
Shine Cardozo
  • 489
  • 5
  • 16

2 Answers2

1

There is no way to reassign a variable in a with template tag.

You should do that in the backend (view) or by loading the variable into JavaScript and perform what you want to do it it can be client-side.

Frederic Perron
  • 777
  • 4
  • 19
0

Like everyone is saying, you can do this logic in the view. But, instead of reassigning a to 2, you can just add 1:

{% with a=1 %}
{% for x in object_list %}
    {% if 'clone' in x.game and a is 1 %}
        <div class="alert alert-primary">
            <h2 class="p-3">{{ x.title }}</h2>
        </div>
        {{ a|add:"1" }} # this is the changed code
    {% endif %}
{% endfor %}
{% endwith %}
Dharman
  • 30,962
  • 25
  • 85
  • 135
theProCoder
  • 390
  • 6
  • 21
  • 1
    oh, sorry, I guess I was writing for Django 3.2 (the latest version at the time of writing). Sorry about that, but I do recommend to start using Django 3 as it has lot's of new features. :) – theProCoder Sep 12 '21 at 01:15