【发布时间】:2012-07-11 20:17:25
【问题描述】:
我正在 GAE、webapp2、jinja2 上构建一个项目,我使用engineauth 进行授权。我需要 Django 的 context_processor 之类的东西,以便在模板中使用来自 webapp2.request 的会话、用户和其他一些变量。请帮我解决这个问题。
【问题讨论】:
标签: google-app-engine jinja2 webapp2
我正在 GAE、webapp2、jinja2 上构建一个项目,我使用engineauth 进行授权。我需要 Django 的 context_processor 之类的东西,以便在模板中使用来自 webapp2.request 的会话、用户和其他一些变量。请帮我解决这个问题。
【问题讨论】:
标签: google-app-engine jinja2 webapp2
有很多方法可以实现这一点。
最简单的方法大概是这样的:
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))
【讨论】: