【问题标题】:Jinja2 Frame Variables in Global Function全局函数中的 Jinja2 帧变量
【发布时间】:2017-03-29 17:55:24
【问题描述】:

我有一个全局函数test

from jinja2.utils import contextfunction

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

在我的测试中,我这样称呼它......

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

test 中以context 结尾的唯一变量是ijk 是“不可读的”。除了将它们传递给test(j, k)

之外,还有什么方法可以访问它们

【问题讨论】:

  • 您是否在模板中使用上下文导入? (例如:{% from 'admin/lib.html' import render_form, render_field, render_form_fields with context %})
  • 为了这个例子,没有导入。在编译的模板上调用render,并将test() 添加到env['globals']
  • 你必须将 j, k 传递给函数。这些变量是 for 块的本地变量,对全局上下文不可用。 j 是不言自明的; k 是本地的,因为 {% set %} doesn't assign to the global context.

标签: python jinja2


【解决方案1】:

根据github issue with a similar concern,您定义为jk 的变量是在本地设置的,而不是全局设置的。您尝试调用的函数将无法识别变量k,除非您将其传递给该函数。这是记录在案的行为。

stackoverflow 相关问题:

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

Jinja2: Change the value of a variable inside a loop

【讨论】:

  • 这也是我的结论。很高兴有一个健全的检查。似乎很奇怪,您无法访问本地块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 2011-04-08
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多