This repository was archived by the owner on Oct 12, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathMako
87 lines (69 loc) · 2.36 KB
/
Mako
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
Here's a simple Tool for Mako templating:
{{{
#!python
import cherrypy
from mako.lookup import TemplateLookup
class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
"""Callable which sets response.body."""
def __init__(self, template, next_handler):
self.template = template
self.next_handler = next_handler
def __call__(self):
env = globals().copy()
env.update(self.next_handler())
try:
return self.template.render(**env)
except:
# something went wrong rendering the template
# this will generate a pretty error page with details
cherrypy.response.status = "500"
return exceptions.html_error_template().render()
class MakoLoader(object):
def __init__(self):
self.lookups = {}
def __call__(self, filename, directories, module_directory=None,
collection_size=-1):
# Find the appropriate template lookup.
key = (tuple(directories), module_directory)
try:
lookup = self.lookups[key]
except KeyError:
lookup = TemplateLookup(directories=directories,
module_directory=module_directory,
collection_size=collection_size,
)
self.lookups[key] = lookup
cherrypy.request.lookup = lookup
# Replace the current handler.
cherrypy.request.template = t = lookup.get_template(filename)
cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler)
main = MakoLoader()
cherrypy.tools.mako = cherrypy.Tool('on_start_resource', main)
}}}
Use it like this:
{{{
#!python
@cherrypy.expose
@cherrypy.tools.mako(filename="index.html")
def index(name=None):
return {'username': name}
}}}
You will also need two config options:
{{{
tools.mako.collection_size = 500
tools.mako.directories = "path/to/templates"
}}}
index.html:
{{{
<html>
<body>
Hello, ${username}!
</body>
</html>
}}}
------
To avoid UTF-8 encoding problems use following for template lookup
{{{
#!python
lookup = TemplateLookup(directories=directories, module_directory=module_directory, collection_size=collection_size,output_encoding='utf-8', encoding_errors='replace')
}}}