jinja2模板中变量的作用域

4

我正在编写基于jinja2模板的应用程序。我试图编写一个设置变量的逻辑。

{% set last_item = none %}
{% for u in users %}
  {% if not u.username == user.username%}
    {% if  g.user.is_bestfriend(u) %}
      {% set last_item = 'true' %}
    {% endif %}
  {% endif %}
{% endfor %}

{{last_item}}

但是在{% endfor %}之后,last_item的值再次被设置为None,而不是True。有没有办法在jinja2模板中将其设置为True


1
看看这个... https://dev59.com/42445IYBdhLWcg3wappH - Andrew Kloos
2个回答

5

从2.10版本开始,您可以使用命名空间变量在进入作用域之前进行设置:

{% set ns = namespace(found=false) %}
{% for item in items %}
    {% if item.check_something() %}
        {% set ns.found = true %}
    {% endif %}
    * {{ item.title }}
{% endfor %}
Found item having something: {{ ns.found }}

另请参阅文档:http://jinja.pocoo.org/docs/2.10/templates/#assignments

这里还有相关的IT技术内容需要翻译。

1
由于jinja2的作用域规则,您无法在设置变量的范围之外访问该变量。抱歉 :(

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接