我正在编写一个自定义jinja2扩展 ,用于flask应用程序,我正在寻找一种方法来使用我正在实现的标签访问模板上下文数据。 也就是说,我希望扩展标记使用传递给模板的上下文参数:
@app.route('/users/<user_id>') def user_page(user_id): ... return render_template('users/index.html', user_id=user_id, active=True)模板:
<!-- I want this tag to see the value of user_id and active --> {% my_jinja2_tag %}我知道我可以使用{{ user_id }}渲染上下文变量,但我正在寻找的是一种检查模板上下文呈现自定义jinja2扩展的方法。 那可行吗? 谢谢。
I'm writing a custom jinja2 extension to use in flask applications and I'm looking for a way to access the templates context data using the tag I'm implementing. That is, I want the extension tag to use context params passed into the template:
@app.route('/users/<user_id>') def user_page(user_id): ... return render_template('users/index.html', user_id=user_id, active=True)The template:
<!-- I want this tag to see the value of user_id and active --> {% my_jinja2_tag %}I know I can render the context variable using {{ user_id }}, but what I'm looking for is a way to inspect the context of the template rendering a custom jinja2 extension. Is that doable? thanks.
最满意答案
ContextReference
是的,可以使用jinja2.nodes.ContextReference() 。 请参阅此处的API参考。
放松一下,我将引导你完成它。 :)
首先是扩展:
class ActiveCheckerExtension(jinja2.ext.Extension): """ This will give us a {% check_active %} tag. """ template = 'Active is : %s' tags = set(['check_active']) def _render_tag(self, context, caller): return jinja2.Markup(self.template % unicode(context['active'])) def parse(self, parser): ctx_ref = jinja2.nodes.ContextReference() lineno = next(parser.stream).lineno node = self.call_method('_render_tag', [ctx_ref], lineno=lineno) return jinja2.nodes.CallBlock(node, [], [], [], lineno=lineno)然后让我们将它添加到Flask的jinja2中。
app.jinja_env.add_extension(ActiveCheckerExtension)现在在模板中,您可以执行以下操作:
{% check_active %}确保在添加标记的所有模板中定义了active ,否则您将获得KeyError因为上下文不具有该模板变量。
ContextReference
Yes, it's possible using jinja2.nodes.ContextReference(). See the API reference here.
Relax, I'm going to guide you through it. :)
First the extension:
class ActiveCheckerExtension(jinja2.ext.Extension): """ This will give us a {% check_active %} tag. """ template = 'Active is : %s' tags = set(['check_active']) def _render_tag(self, context, caller): return jinja2.Markup(self.template % unicode(context['active'])) def parse(self, parser): ctx_ref = jinja2.nodes.ContextReference() lineno = next(parser.stream).lineno node = self.call_method('_render_tag', [ctx_ref], lineno=lineno) return jinja2.nodes.CallBlock(node, [], [], [], lineno=lineno)Then let's add it to Flask's jinja2.
app.jinja_env.add_extension(ActiveCheckerExtension)Now in your template, you can do:
{% check_active %}Make sure active is defined in all the templates you add the tag to, or else you'll get a KeyError because the context won't have that template variable.
更多推荐
发布评论