问题描述
以下是我需要更新变量的代码。
{% 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 %}
但是,它没有将 {{ a=2 }}
设置为 2,而是抛出以下错误:
a
解决方法
无法在 with
模板标签中重新分配变量。
您应该在后端(视图)中执行此操作,或者通过将变量加载到 JavaScript 中并执行您想要执行的操作,它可以在客户端执行。
,正如大家所说,您可以在视图中执行此逻辑。但是,您不必将 a
重新分配给 2,而是只需添加 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 %}