在我的主线中,我想在模板呈现后从当前模板上下文中读取一个变量。 此变量已被“设置”为模板。我可以在上下文函数中访问该变量,但是如何在我的主线中访问它。如何读取jinja上下文变量
result = template.render({'a' : "value-1" })
# in the template {% set b = "value-2" %}
b = ?
更新:我在webapp2源代码中找到了一个解决方案。该生产线是:
b = template.module.b
在我的主线中,我想在模板呈现后从当前模板上下文中读取一个变量。 此变量已被“设置”为模板。我可以在上下文函数中访问该变量,但是如何在我的主线中访问它。如何读取jinja上下文变量
result = template.render({'a' : "value-1" })
# in the template {% set b = "value-2" %}
b = ?
更新:我在webapp2源代码中找到了一个解决方案。该生产线是:
b = template.module.b
我发现,在webapp2-extras源代码的帮助下,可以在python主线访问当前的jinja上下文。另请参阅:jinja文档中的class jinja2.Template。
Python的主线:
result = template.render({'a' : "value-1" })
# in the template {% set b = "value-2" %}
b = template.module.b
感谢您的帮助。
我不建议你做你要求什么,而是想更好的解决办法,反正这里是哈克回答:
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'
我在查找webapp2代码后发现了另一个解决方案。该行是: b = template.module.b – voscausa
很棒的发现!感谢分享。 – Ski