如何读取jinja上下文变量
在我的主程序中,我想在模板渲染完成后,从当前的模板上下文中读取一个变量。这个变量是由模板设置的。我可以在上下文函数中访问这个变量,但我不知道如何在我的主程序中访问它。
result = template.render({'a' : "value-1" })
# in the template {% set b = "value-2" %}
b = ?
更新:我在webapp2的源代码中找到了一个解决方案。那一行是:
b = template.module.b
2 个回答
0
我不建议你按照你问的那样做,还是想想更好的解决办法。不过,下面是一个比较“hacky”的答案:
from jinja2 import Template
class MyImprovedTemplate(Template):
def render(self, *args, **kwargs):
# this is copy-pasted from jinja source, context added to return
vars = dict(*args, **kwargs)
context = self.new_context(vars)
try:
return context, concat(self.root_render_func(context))
except Exception:
exc_info = sys.exc_info()
return context, self.environment.handle_exception(exc_info, True)
>>> t = MyImprovedTemplate('{% set b = 2 %}')
>>> context, s = t.render()
>>> context['b']
'2'
3
我发现,通过查看webapp2-extras的源代码,可以在Python的主程序中访问当前的jinja上下文。你也可以查看jinja文档中的jinja2.Template类。
Python主程序:
result = template.render({'a' : "value-1" })
# in the template {% set b = "value-2" %}
b = template.module.b
谢谢你的帮助。