| 1 |
|
|---|
| 2 |
|
|---|
| 3 |
|
|---|
| 4 |
|
|---|
| 5 |
|
|---|
| 6 |
|
|---|
| 7 |
|
|---|
| 8 |
|
|---|
| 9 |
|
|---|
| 10 |
|
|---|
| 11 |
|
|---|
| 12 |
|
|---|
| 13 |
|
|---|
| 14 |
|
|---|
| 15 |
|
|---|
| 16 |
|
|---|
| 17 |
|
|---|
| 18 |
|
|---|
| 19 |
|
|---|
| 20 |
|
|---|
| 21 |
|
|---|
| 22 |
|
|---|
| 23 |
|
|---|
| 24 |
|
|---|
| 25 |
|
|---|
| 26 |
|
|---|
| 27 |
|
|---|
| 28 |
|
|---|
| 29 |
|
|---|
| 30 |
import cherrypy |
|---|
| 31 |
|
|---|
| 32 |
import kid |
|---|
| 33 |
|
|---|
| 34 |
class KidRender(cherrypy.Tool): |
|---|
| 35 |
def __init__(self, name=None, priority = 0): |
|---|
| 36 |
self._name = name |
|---|
| 37 |
self._point = 'before_handler' |
|---|
| 38 |
self._priority = priority |
|---|
| 39 |
self._templatecache = {} |
|---|
| 40 |
|
|---|
| 41 |
def callable(self, template, output=None, encoding='utf-8', |
|---|
| 42 |
assume_encoding='utf-8'): |
|---|
| 43 |
''' |
|---|
| 44 |
A simple template rendering mechanism using a trivial cache. By |
|---|
| 45 |
default generates xhtml output using utf-8 encoding. The |
|---|
| 46 |
dictionary returned by your exposed method is transformed by kid |
|---|
| 47 |
into the proper output. |
|---|
| 48 |
|
|---|
| 49 |
Most of the time the defaults are good enough |
|---|
| 50 |
|
|---|
| 51 |
@param template: The name of the template to be imported |
|---|
| 52 |
@param output: The type transform to perform. See |
|---|
| 53 |
http://kid-templating.org/guide.html#common-output-methods for |
|---|
| 54 |
possible values. |
|---|
| 55 |
@param encoding: Character encoding to use in the output |
|---|
| 56 |
@param assume_encoding: Format to use when parsing the kid template |
|---|
| 57 |
''' |
|---|
| 58 |
cherrypy.request._handler = cherrypy.request.handler |
|---|
| 59 |
def wrap(*args, **kwargs): |
|---|
| 60 |
ret = cherrypy.request._handler(*args, **kwargs) |
|---|
| 61 |
templ = self._templatecache.get(template, None) |
|---|
| 62 |
if not templ: |
|---|
| 63 |
templ = kid.import_template(name=template) |
|---|
| 64 |
self._templatecache[template] = templ |
|---|
| 65 |
t = templ.Template(**ret) |
|---|
| 66 |
t.assume_encoding=assume_encoding |
|---|
| 67 |
out = t.serialize(output=output, encoding=encoding) |
|---|
| 68 |
if output is None or 'xhtml' in output: |
|---|
| 69 |
if 'application/xhtml+xml' in cherrypy.request.headers['Accept']: |
|---|
| 70 |
cherrypy.response.headers['Content-Type'] = 'application/xhtml+xml' |
|---|
| 71 |
else: |
|---|
| 72 |
|
|---|
| 73 |
cherrypy.response.headers['Content-Type'] = 'text/html; charset=%s' % encoding |
|---|
| 74 |
return out |
|---|
| 75 |
|
|---|
| 76 |
cherrypy.request.handler = wrap |
|---|
| 77 |
|
|---|