问题描述
我有以下Jinja模板:
I have the following Jinja template:
{% 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
.
If the condition is met in the for
loop, I'd like to change mybool
to true so I can display mybool is true!
below. However, it looks like the scope of the inner mybool
is limited to the if
statement, so the desired mybool
is never set.
如何设置全局" mybool
,以便可以在最后一个if
语句中使用它?
How can I set the "global" mybool
so I can use it in the last if
statement?
编辑
我找到了(仅正确缓存了网页浏览量),但它们似乎不起作用.也许他们在Jinja2中已弃用...
I've found some suggestions (only the cached page views correctly), but they don't seem to work. Perhaps they're deprecated in Jinja2...
编辑
下面提供的解决方案.我仍然很好奇为什么以上建议没有用.有谁能确定他们已被弃用?
Solution provided below. I am still curious why the suggestions above do not work though. Does anyone know for sure that they were deprecated?
推荐答案
解决此限制的一种方法是启用执行"表达式语句扩展,并使用数组而不是布尔值:
One way around this limitation is to enable the "do" expression-statement extension and use an array instead of boolean:
{% 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",])
To enable Jinja's "do" expression-statement extension: e = jinja2.Environment(extensions=["jinja2.ext.do",])
这篇关于Jinja变量的范围可以扩展到内部块之外吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!