Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 Frame Variables in Global Function

Tags:

python

jinja2

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)

like image 672
Shaun Avatar asked Jan 30 '26 01:01

Shaun


1 Answers

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

like image 158
Joseph Farah Avatar answered Jan 31 '26 14:01

Joseph Farah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!