Search code examples
djangodjango-templatesjinja2with-statement

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


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'

Solution

  • 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.