Skip to content

Loop variables in custom python contextfunction #768

@captainmalloc

Description

@captainmalloc

Hi,

I am experiencing an unexpected behavior with Jinja and local variables in a for loop when accessing them from a custom Python context function.

Expected Behavior

I expected for every variable to be available in the context object in a python @contextfunction, even if it is defined/updated in a for loop.

Actual Behavior

The actual behavior is that only variables defined/updated outside the loop are available/have the expected value.

Template Code

Here is a simple template code to demonstrate the behavior:

>>> import jinja2
>>> jinja2.__version__
'2.9.4'
>>> @jinja2.contextfunction
... def myContextFunction(ctx):
...     return "myContextFunction: ctx['myI'] = " + str(ctx['myI'])
...
>>> tmplt = """
... {% for i in range(2): %}
... {%- set  myI = i -%}
...     {{ myContextFunction() }}
...     In template myI = {{ myI }}
... {% endfor %}
... """
>>> template = jinja2.Template(tmplt)
>>> template.globals['myContextFunction'] = myContextFunction
>>> template.render()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/arm/tools/python/jinja2_py2.7.8/2.9.4/rhe6-x86_64/lib/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "/arm/tools/python/jinja2_py2.7.8/2.9.4/rhe6-x86_64/lib/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<template>", line 4, in top-level template code
  File "<stdin>", line 3, in myContextFunction
  File "/arm/tools/python/jinja2_py2.7.8/2.9.4/rhe6-x86_64/lib/jinja2/runtime.py", line 253, in __getitem__
    raise KeyError(key)
KeyError: 'myI'
>>> context = {'myI' : 0}
>>> print template.render(**context)

myContextFunction: ctx['myI'] = 0
        In template myI = 0
myContextFunction: ctx['myI'] = 0
        In template myI = 1

My first goal was to access the i counter, or also the loop.index from my custom contextfunction. Also those variable, I expected to be defined in context, where not available.

Your Environment

  • Python version: Python 2.7.8
  • Jinja version: '2.9.4'

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions