webapp2 + jinja2: How can i get uri_for() working in jinja2-views

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-29 23:09:49

You must set uri_for as a global variable. One way to do it is to set an initializer for global variables and filters:

import webapp2
from webapp2_extras import jinja2

def jinja2_factory(app):
    j = jinja2.Jinja2(app)
    j.environment.filters.update({
        # Set filters.
        # ...
    })
    j.environment.globals.update({
        # Set global variables.
        'uri_for': webapp2.uri_for,
        # ...
    })
    return j

class BaseHandler(webapp2.RequestHandler):

    @webapp2.cached_property
    def jinja2(self):
        # Returns a Jinja2 renderer cached in the app registry.
        return jinja2.get_jinja2(factory=jinja2_factory)

    def render_response(self, _template, **context):
        # Renders a template and writes the result to the response.
        rv = self.jinja2.render_template(_template, **context)
        self.response.write(rv)

Edit: changed example to use a RequestHandler.

Here's the easier solution.. ;-) i have... many people already might know this but works great.

env = jinja2.Environment(
    loader=jinja2.FileSystemLoader(root_path),
    extensions=['jinja2.ext.autoescape',
        'jinja2.ext.i18n',
        CompilerExtension],
    variable_start_string='[[',
    variable_end_string=']]',
    autoescape=True)
env.globals = {
    'uri_for': webapp2.uri_for
}

env.globals is the key :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!