pythonjinja2

Jinja2 Frame Variables in Global Function


I have a global function test

from jinja2.utils import contextfunction

@contextfunction
def test(context):
    context.get_all()

And in my test I'm calling it like this...

{% set i = 0 %}
{% for j in range(0, 10) %}
   {% set k = 0 %}
   {{ test() }}
{% endfor %}

The only variable that end up in the context in test is i. j and k are "unreadable". Is there any way to access them other than passing them into test(j, k)


Solution

  • According to a github issue with a similar concern, the variables you have defined as j and k are set locally, and not globally. The function you are attempting to call will not recognize the variable k unless you pass it to the function. This is documented behavior.

    Related stackoverflow questions:

    Can a Jinja variable's scope extend beyond in an inner block?

    Jinja2: Change the value of a variable inside a loop