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 passed as a dict.
from genshi.output import DocType from genshi.template import TemplateLoader 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) 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})
and in the template itself you will use name with a simple ${name} call.
Last modified 16 years ago
Last modified on Jul 24, 2008, 10:36:47 PM