如何解决如何更新 Django 模板中由“with”设置的变量
以下是我需要更新变量的代码。
{% 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 %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。