jinja2 模板中变量的范围

use*_*896 5 scope jinja2 conditional-statements

我正在编写基于 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}}
Run Code Online (Sandbox Code Playgroud)

但之后{% endfor %}last_item值再次设置为 none,而不是 true。有什么方法可以在 jinja2 模板中将其设置为 true 吗?

gan*_*opp 6

从版本 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 }}
Run Code Online (Sandbox Code Playgroud)

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


nat*_*own 1

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