{% 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?
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.
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.
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.
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.
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With