jinja2模板中变量的范围

时间:2014-05-10 05:43:08

标签: scope conditional-statements jinja2

我正在编写基于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?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

从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