Edgewall Software


Version 2 (modified by mitsuhiko, 6 years ago)

mitsuhiko approved it

Genshi Recipes: Using Genshi with Werkzeug

 Werkzeug is a WSGI utility framework.

Templated Response class

This class cuts back on the standard calls to load the template, generate a stream and populate it with data and subsequently render it. The data parameter is best passed as a dict.

from werkzeug import Response as ResponseBase

TEMPLATES_DIR = # some path

class Response(ResponseBase):
    """Subclass of base responses that has a default mimetype of text/html."""
    default_mimetype = "text/html"

class TemplatedResponse(Response):
    """Response class with built in template renderer."""

    loader = None

    def __init__(self, template, data):
        if TemplatedResponse.loader is None:
            TemplatedResponse.loader = TemplateLoader(TEMPLATES_DIR, auto_reload=True)
        self.template = self.loader.load(template)
        self.stream = self.template.generate(data=data)
        response = self.stream.render('xhtml', doctype=DocType.XHTML_STRICT)
        Response.__init__(self, response)

Within your code you can then import this class and do something like:

return TemplatedResponse(template='my_template.html', data={'name': some_variable})