1. b.93z.org
  2. Notes

Template rendering in webapp

For some people writing code like this in every handler’s method isn’t very good:

path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))

I totally agree with them, so I wrote very simple subclass of webapp.RequestHandler:

from os.path import join, dirname

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template


class RequestHandler(webapp.RequestHandler):

    def render(self, tmpl, ctx={}):
        if hasattr(self, 'get_additional_ctx'):
            ctx.update(self.get_additional_ctx())
        path = join(dirname(__file__), 'templates/', tmpl)
        self.response.out.write(template.render(path, ctx))

Example usage:

from google.appengine.api import users

from util import RequestHandler


class AdminRequestHandler(RequestHandler):

    def get_additional_ctx(self):
        return {
            'logout_url': users.create_logout_url(self.request.uri),
        }


class IndexHandler(AdminRequestHandler):

    def get(self):
        self.render('admin/index.html', {'greeting': 'Hello, World!'})

This is not the only way to do this, but the simplest.

© 2008–2017 93z.org