Search code examples
google-app-enginejinja2webapp2

webapp2 jinja2 context_processor


I am building a project on GAE, webapp2, jinja2 and I use engineauth for authorization. I need something like Django's context_processor in order to use session, user and some other variables from webapp2.request in templates. Please, help me to solve this problem.


Solution

  • There are many ways to achieve this.

    The simplest way probably looks like this:

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

    I like when my variables are in template globals, then I can access them in my template widgets without having to pass around bunch of vars in template. So I am doing it like this:

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

    There are other methods in: Context processor using Werkzeug and Jinja2