Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2: local/global variable

Tags:

flask

jinja2

{% set disabled = '' %}
{% for voter in record.voters %}
    {% if user == voter %}
        {% set disabled = 'disabled' %}
    {% endif %}
    {{ disabled }}  # outputs: 'disabled'
{% endfor %}
{{ disabled }}  # outputs: ''

I have that template in Jinja2. What I need is 'disabled' variable to be visible outside 'for' loop. Is that possible?

like image 206
c00p3r.web Avatar asked Jul 29 '13 13:07

c00p3r.web


People also ask

Why can’t I modify a Jinja2 global scope variable inside a loop?

When using jinja2 for SaltStack formulas you may be surprised to find that your global scoped variables do not have ability to be modified inside a loop. Although this is counter intuitive given the scope behavior of most scripting languages it is unfortunately the case that a jinja2 globally scoped variable cannot be modified from an inner scope.

What is the default type of a variable in Jinja?

Default type is Undefined, but there are other types available, StrictUndefined being the most useful one. By using StrictUndefined type we tell Jinja to raise error whenever there's an attempt at using undefined variable.

How to modify a global array in Jinja2?

The solution involves enabling the do extension for Jinja2 and using it to modify a global array. To enable the extension use: Show activity on this post. 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.

How to access variables in Jinja2 Playbook?

So the variable was accessed using { { my_name }} where { { }} is referred as Jinja2 syntax. This was a simple method to access any variable inside the playbook. Filters are same as small functions, or methods, that can be run on the variable. Some filters operate without arguments, some take optional arguments, and some require arguments.


1 Answers

As of version 2.10 more complex use cases can be handled using namespace objects which allow propagating of changes across scopes:

{% 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 }}
like image 139
mobin Avatar answered Oct 07 '22 01:10

mobin