|
1 """ |
|
2 Template handler |
|
3 """ |
|
4 |
|
5 # use Mako |
|
6 from mako import exceptions |
|
7 from mako.template import Template |
|
8 from mako.lookup import TemplateLookup |
|
9 |
|
10 # for http.ResponseError |
|
11 import http |
|
12 |
|
13 # path to template files |
|
14 TEMPLATE_DIR = "templates" |
|
15 |
|
16 # path to cached templates |
|
17 CACHE_DIR = "cache/templates" |
|
18 |
|
19 # template file extension |
|
20 TEMPLATE_EXT = "tmpl" |
|
21 |
|
22 |
|
23 # our Mako template lookup handler |
|
24 _lookup = TemplateLookup(directories=[TEMPLATE_DIR], module_directory=CACHE_DIR) |
|
25 |
|
26 |
|
27 class TemplateError (http.ResponseError) : |
|
28 """ |
|
29 Raised by the template module functions |
|
30 """ |
|
31 |
|
32 pass |
|
33 |
|
34 def lookup (name) : |
|
35 """ |
|
36 Looks up a template based on the bare "name", which does not include the path or file extension |
|
37 """ |
|
38 |
|
39 try : |
|
40 return _lookup.get_template("%s.%s" % (name, TEMPLATE_EXT)) |
|
41 |
|
42 except : |
|
43 raise TemplateError("Template broken: %r" % (name, ), status='500 Internal Server Error', details=exceptions.text_error_template().render()) |
|
44 |
|
45 def load (path) : |
|
46 """ |
|
47 Loads a template from a specific file |
|
48 """ |
|
49 |
|
50 try : |
|
51 return Template(filename=path, module_directory=CACHE_DIR) |
|
52 |
|
53 except : |
|
54 raise TemplateError("Template broken: %r" % (path, ), status='500 Internal Server Error', details=exceptions.text_error_template().render()) |
|
55 |
|
56 def render_template (tpl, **params) : |
|
57 """ |
|
58 Render the given template, returning the output, or raising a TemplateError |
|
59 """ |
|
60 |
|
61 try : |
|
62 return tpl.render(**params) |
|
63 |
|
64 except : |
|
65 raise TemplateError("Template render failed", status='500 Internal Server Error', details=exceptions.text_error_template().render()) |
|
66 |
|
67 def render (name, **params) : |
|
68 """ |
|
69 Render a template, using lookup() on the given name |
|
70 """ |
|
71 |
|
72 return render_template(lookup(name), **params) |
|
73 |
|
74 def render_file (path, **params) : |
|
75 """ |
|
76 Render a template, using load() on the given path |
|
77 """ |
|
78 |
|
79 return render_template(load(path), **params) |
|
80 |