python - How can a custom jinja2 tag interface with the context of a flask request -
i'm writing custom jinja2
extension use in flask
applications , i'm looking way access templates context data using tag i'm implementing. is, want extension tag use context params passed 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:
<!-- want tag see value of user_id , active --> {% my_jinja2_tag %}
i know can render context variable using {{ user_id }}
, i'm looking way inspect context of template rendering custom jinja2 extension. doable? thanks.
contextreference
yes, it's possible using jinja2.nodes.contextreference()
. see api reference here.
relax, i'm going guide through it. :)
first extension:
class activecheckerextension(jinja2.ext.extension): """ give {% check_active %} tag. """ template = 'active : %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 flask's jinja2.
app.jinja_env.add_extension(activecheckerextension)
now in template, can do:
{% check_active %}
make sure active
defined in templates add tag to, or else you'll keyerror
because context won't have template variable.
Comments
Post a Comment