4

I am writing jinja2 template based application. I am trying to write a logic to set variable.

{% 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}}

but after {% endfor %}, last_item value is again set to none, instead of true. Is there any way to set it to true in jinja2 template?

wcarhart
  • 2,685
  • 1
  • 23
  • 44
user3526896
  • 129
  • 1
  • 3
  • 11
  • 1
    Check this out... http://stackoverflow.com/questions/4870346/can-a-jinja-variables-scope-extend-beyond-in-an-inner-block – Andrew Kloos May 12 '14 at 16:07

2 Answers2

4

Since version 2.10 you can do this using a namespace variable, set before entering the scope:

{% 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 }}

See also the documentation: http://jinja.pocoo.org/docs/2.10/templates/#assignments

ganzpopp
  • 364
  • 3
  • 12
1

Due to scoping rules in jinja2, you cannot access a variable outside the scope that it was set in. Sorry :(

nathanielobrown
  • 992
  • 7
  • 15