How do I update a variable set by 'with' in Django Template

Viewed 2037

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'
2 Answers

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.

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