3

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)

Shaun
  • 3,777
  • 4
  • 25
  • 46
  • are you importing with context in the template? (eg.: {% from 'admin/lib.html' import render_form, render_field, render_form_fields with context %} ) – rll Nov 23 '16 at 19:42
  • For sake of this example, there is no import. `render` is called on the compiled template and `test()` is added to the `env['globals']` – Shaun Nov 23 '16 at 19:44
  • You have to pass j, k to the function. Those variables are local to the for block and not available to the global context. j is self-explanatory; k is local because [`{% set %}` doesn't assign to the global context](https://github.com/pallets/jinja/issues/164). – approxiblue Nov 26 '16 at 20:35

1 Answers1

2

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

Community
  • 1
  • 1
Joseph Farah
  • 2,463
  • 2
  • 25
  • 36
  • 1
    This was my conclusion as well. Good to have a sanity check. Seems strange you can't access the local block. – Shaun Nov 28 '16 at 16:06