diff -r d6a8258bd90e -r 0ce1f471e9d7 lib/template.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lib/template.py Fri Feb 06 22:48:00 2009 +0200 @@ -0,0 +1,80 @@ +""" + Template handler +""" + +# use Mako +from mako import exceptions +from mako.template import Template +from mako.lookup import TemplateLookup + +# for http.ResponseError +import http + +# path to template files +TEMPLATE_DIR = "templates" + +# path to cached templates +CACHE_DIR = "cache/templates" + +# template file extension +TEMPLATE_EXT = "tmpl" + + +# our Mako template lookup handler +_lookup = TemplateLookup(directories=[TEMPLATE_DIR], module_directory=CACHE_DIR) + + +class TemplateError (http.ResponseError) : + """ + Raised by the template module functions + """ + + pass + +def lookup (name) : + """ + Looks up a template based on the bare "name", which does not include the path or file extension + """ + + try : + return _lookup.get_template("%s.%s" % (name, TEMPLATE_EXT)) + + except : + raise TemplateError("Template broken: %r" % (name, ), status='500 Internal Server Error', details=exceptions.text_error_template().render()) + +def load (path) : + """ + Loads a template from a specific file + """ + + try : + return Template(filename=path, module_directory=CACHE_DIR) + + except : + raise TemplateError("Template broken: %r" % (path, ), status='500 Internal Server Error', details=exceptions.text_error_template().render()) + +def render_template (tpl, **params) : + """ + Render the given template, returning the output, or raising a TemplateError + """ + + try : + return tpl.render(**params) + + except : + raise TemplateError("Template render failed", status='500 Internal Server Error', details=exceptions.text_error_template().render()) + +def render (name, **params) : + """ + Render a template, using lookup() on the given name + """ + + return render_template(lookup(name), **params) + +def render_file (path, **params) : + """ + Render a template, using load() on the given path + """ + + return render_template(load(path), **params) +