我有以下 Jinja 模板:
{% set mybool = False %}
{% for thing in things %}
<div class='indent1'>
<ul>
{% if current_user %}
{% if current_user.username == thing['created_by']['username'] %}
{% set mybool = True %}
<li>mybool: {{ mybool }}</li> <!-- prints True -->
<li><a href='#'>Edit</a></li>
{% endif %}
{% endif %}
<li>Flag</li>
</ul>
</div>
<hr />
{% endfor %}
{% if not mybool %}
<!-- always prints this -->
<p>mybool is false!</p>
{% else %}
<p>mybool is true!</p>
{% endif %}
如果 for
循环中满足条件,我想将 mybool
更改为 true,以便可以显示 mybool is true!
下面。但是,内部 mybool
的范围似乎仅限于 if
语句,因此期望的 mybool
从未设置。
如何设置“全局”mybool
以便我可以在最后一个 if
语句中使用它?
编辑
我找到了some suggestions (只有正确缓存的页面 View ),但它们似乎不起作用。也许它们在 Jinja2 中已被弃用...
编辑
下面提供了解决方案。我仍然很好奇为什么上面的建议不起作用。有谁确切知道它们已被弃用?
最佳答案
解决此限制的一种方法是启用 "do" expression-statement extension并使用数组而不是 bool 值:
{% set exists = [] %}
{% for i in range(5) %}
{% if True %}
{% do exists.append(1) %}
{% endif %}
{% endfor %}
{% if exists %}
<!-- exists is true -->
{% endif %}
要启用 Jinja 的“do”表达式语句扩展:e = jinja2.Environment(extensions=["jinja2.ext.do",])
关于templates - Jinja 变量的范围可以超出内部 block 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4870346/