如何在 Django 模板中更新 'with' 设置的变量
How do I update a variable set by 'with' in Django Template
以下是我需要更新变量的代码。
{% 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 }}
将 a
设置为 2,而是抛出以下错误:
TemplateSyntaxError at /
Could not parse the remainder: '=2' from 'a=2'
无法在 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 %}
以下是我需要更新变量的代码。
{% 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 }}
将 a
设置为 2,而是抛出以下错误:
TemplateSyntaxError at /
Could not parse the remainder: '=2' from 'a=2'
无法在 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 %}