【问题标题】:webapp2 jinja2 context_processorwebapp2 jinja2 context_processor
【发布时间】:2012-07-11 20:17:25
【问题描述】:

我正在 GAE、webapp2、jinja2 上构建一个项目,我使用engineauth 进行授权。我需要 Django 的 context_processor 之类的东西,以便在模板中使用来自 webapp2.request 的会话、用户和其他一些变量。请帮我解决这个问题。

【问题讨论】:

    标签: google-app-engine jinja2 webapp2


    【解决方案1】:

    有很多方法可以实现这一点。

    最简单的方法大概是这样的:

    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))
    

    还有其他方法在:Context processor using Werkzeug and Jinja2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-28
      • 2013-10-24
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      • 2018-06-09
      • 2018-06-07
      相关资源
      最近更新 更多