2
我在GAE,webapp2,jinja2上構建一個項目,我使用engineauth進行授權。我需要像Django的context_processor
這樣的模板來使用webapp2.request中的會話,用戶和其他一些變量。請幫我解決這個問題。webapp2 jinja2 context_processor
我在GAE,webapp2,jinja2上構建一個項目,我使用engineauth進行授權。我需要像Django的context_processor
這樣的模板來使用webapp2.request中的會話,用戶和其他一些變量。請幫我解決這個問題。webapp2 jinja2 context_processor
有很多方法可以做到這一點。
最簡單的方法可能是這樣的:
def extra_context(handler, context=None):
"""
Adds extra context.
"""
context = context or {}
# You can load and run various template processors from settings like Django does.
# I don't do this in my projects because I'm not building yet another framework
# so I like to keep it simple:
return dict({'request': handler.request}, **context)
# --- somewhere in response handler ---
def get(self):
my_context = {}
template = get_template_somehow()
self.response.out.write(template.render(**extra_context(self, my_context))
我喜歡當我的變量是模板全局,那麼我可以訪問他們在我的模板控件,而無需一堆周圍的瓦爾傳遞模板。所以,我這樣做是這樣的:
def get_template_globals(handler):
return {
'request': handler.request,
'settings': <...>
}
class MyHandlerBase(webapp.RequestHandler):
def render(self, context=None):
context = context or {}
globals_ = get_template_globals(self)
template = jinja_env.get_template(template_name, globals=globals_)
self.response.out.write(template.render(**context))