3

I would like to set a flag inside a Jinja2 template for loop and later display something or not depending on the flag like so:

{% set foobar = False %}
{% for foo in foos %}
   [... render the foo here ...]
   {% if foo.bar %}
      {% set foobar = True %}
   {% endif %}
{% endfor %}
[...]
{% if foobar %}
  At least one of the foos is bar!!!
{% endif %}

It seems however that this is impossible and the foobar set within the loop is not the same as the one outside the loop. Even if foo.bar evaluates to True for one of the foos, foobar remains False outside the loop.

Is there any way of doing this with template code only and without iterating over all the foos again?

NiklasMM
  • 2,895
  • 2
  • 22
  • 26

1 Answers1

3

I don't think this is directly supported by Jinja2.

IMO the best would be to avoid it entirely and precompute as much data as possible outside of the template.

If you can't avoid doing this in the template, there are ways to hack around it, e.g. using a dictionary or some custom object:

{% set foobar = {'value': False} %}
{% for foo in foos %}
    [... render the foo here ...]
    {% if foo.bar %}
        {% if foobar.update({'value': foo.bar}) %}
        {% endif %}
    {% endif %}
{% endfor %}
[...]
{% if foobar['value'] %}
    At least one of the foos is bar!!!
{% endif %}
famousgarkin
  • 13,687
  • 5
  • 58
  • 74
  • Thank you! And sure I could precompute the value of the flag, but I find that to be more ugly than to do it inline. – NiklasMM Jun 03 '15 at 06:31