| | 1 | = Genshi Recipes: Using Genshi with Werkzeug = |
| | 2 | |
| | 3 | [http://werkzeug.pocoo.org/ Werkzeug] is a WSGI utility framework. |
| | 4 | |
| | 5 | == Templated Response class == |
| | 6 | |
| | 7 | 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. |
| | 8 | |
| | 9 | {{{ |
| | 10 | #!python |
| | 11 | from werkzeug import Response as BaseResponse |
| | 12 | |
| | 13 | TEMPLATES_DIR = # some path |
| | 14 | |
| | 15 | class Response(BaseResponse): |
| | 16 | """Subclass of base responses that has a default mimetype of text/html.""" |
| | 17 | default_mimetype = "text/html" |
| | 18 | |
| | 19 | class TemplatedResponse(Response): |
| | 20 | """Response class with built in template renderer.""" |
| | 21 | |
| | 22 | loader = None |
| | 23 | |
| | 24 | def __init__(self, template, data): |
| | 25 | if TemplatedResponse.loader is None: |
| | 26 | TemplatedResponse.loader = TemplateLoader(TEMPLATES_DIR, auto_reload=True) |
| | 27 | self.template = self.loader.load(template) |
| | 28 | self.stream = self.template.generate(data=data) |
| | 29 | self.response = self.stream.render('xhtml', doctype=DocType.XHTML_STRICT) |
| | 30 | |
| | 31 | Response.__init__(self, self.response) |
| | 32 | }}} |
| | 33 | |
| | 34 | Within your code you can then import this class and do something like: |
| | 35 | |
| | 36 | {{{ |
| | 37 | #!python |
| | 38 | return TemplatedResponse(template='my_template.html', data={'name': some_variable}) |
| | 39 | }}} |