template:
{% set foo = "bar" %}
foo - {{ foo }}
{% for i in range(2) %}
for:foo - {{ foo }}
{% set foo = i %}
for:foo - {{ foo }}
{% endfor %}
{{ foo }}
{% block test %}
block:foo - {{ foo }}
{% set foo = "baz" %}
block:foo - {{ foo }}
{% endblock %}
foo - {{ foo }}
result:
foo - bar
for:foo - bar
for:foo - 0
for:foo - 0
for:foo - 1
foo - bar
block:foo - bar
block:foo - baz
foo - bar
wtf?
Please make a method of assigning a global variable.
Chipping in with some more details. This is what the code above looks like to get a feeling for what's happening inside:
from jinja2.runtime import LoopContext, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join, to_string, identity, TemplateNotFound
name = None
def root(context, environment=environment):
...
l_foo = 'bar'
context.vars['foo'] = l_foo
context.exported_vars.add('foo')
yield u'\nfoo - %s\n\n' % (
l_foo,
)
t_1 = l_foo
l_i = missing
for l_i in context.call(l_range, 2):
if 0: yield None
yield u'\n for:foo - %s\n ' % (
l_foo,
)
l_foo = l_i
yield u'\n for:foo - %s\n ' % (
l_foo,
)
l_foo = t_1
l_i = missing
yield u'\n\n'
for event in context.blocks['test'][0](context):
yield event
yield u'\n\nfoo - '
yield to_string(l_foo)
def block_test(context, environment=environment):
l_foo = context.resolve('foo')
if 0: yield None
yield u'\n block:foo - %s\n ' % (
l_foo,
)
l_foo = 'baz'
yield u'\n block:foo - %s\n' % (
l_foo,
)
blocks = {'test': block_test}
debug_info = '2=8&3=12&5=16&6=19&7=21&8=23&11=28&17=31&11=33&12=37&13=39&14=41'
More details:
Globals: http://jinja.pocoo.org/docs/api/#global-namespace
General: http://jinja.pocoo.org/docs/templates/#assignments
Implementation: http://jinja.pocoo.org/docs/api/#jinja2.runtime.Context
Another good explanation: http://stackoverflow.com/a/3355029/482864
Any ideas?
This is documented behavior.
mitsuhiko,
We have the same problem as DriverX.
Yes, the use of "set" is documented, but, is it working?
Our example:
{% set the_var = 'foo' %} {% for e in elements %} {% set the_var = 'YES' %} the var: {{ the_var }} {%- endfor %} the_var: {{ the_var }}
Result:
the_var: YES the_var: YES the_var: foo
Can you help us? Thanks
http://stackoverflow.com/questions/4870346/can-a-jinja-variables-scope-extend-beyond-in-an-inner-block and http://stackoverflow.com/questions/9486393/jinja2-change-the-value-of-a-variable-inside-a-loop
I really don't understand why those hacks are neccesary, should be "local var" syntax or similar
Regards
Most helpful comment
mitsuhiko,
We have the same problem as DriverX.
Yes, the use of "set" is documented, but, is it working?
Our example:
Result:
Can you help us? Thanks