Jinja2: local/global variable

The easiest way to handle this is to move the logic that sets the disabled variable to your view function and send it down to the template ready to be used. Mixing application logic with presentation is not a good idea, templates should receive the data as digested as possible.

That said, there is an ugly hack that makes what you want possible, shown in the accepted answer to this question.

The solution involves enabling the do extension for Jinja2 and using it to modify a global array. To enable the extension use:

app.jinja_env.add_extension('jinja2.ext.do')

Here is the solution adapted to your example:

{% set disabled = [] %}
{% for voter in record.voters %}
    {% if user == voter %}
        {% do disabled.append(1) %}
    {% endif %}
{% endfor %}
{% if disabled %}
    disabled
{% endif %}

You can use an array/dict like Miguel suggests, but you do not need the do extension per se; you can set a dummy var. I use the following:

{% set glob={} %}

at the top, and then in my code:

{% set _ = glob.update({'disabled':True}) %}

The _ variables is just a dummy, you don't use it afterwards.

Tags:

Jinja2

Flask