terom@150: """ terom@150: Template handler terom@150: """ terom@150: terom@150: # use Mako terom@150: from mako import exceptions terom@150: from mako.template import Template terom@150: from mako.lookup import TemplateLookup terom@150: terom@150: # for http.ResponseError terom@150: import http terom@150: terom@150: # path to template files terom@150: TEMPLATE_DIR = "templates" terom@150: terom@150: # path to cached templates terom@150: CACHE_DIR = "cache/templates" terom@150: terom@150: # template file extension terom@150: TEMPLATE_EXT = "tmpl" terom@150: terom@150: terom@150: # our Mako template lookup handler terom@150: _lookup = TemplateLookup(directories=[TEMPLATE_DIR], module_directory=CACHE_DIR) terom@150: terom@150: terom@150: class TemplateError (http.ResponseError) : terom@150: """ terom@150: Raised by the template module functions terom@150: """ terom@150: terom@150: pass terom@150: terom@150: def lookup (name) : terom@150: """ terom@150: Looks up a template based on the bare "name", which does not include the path or file extension terom@150: """ terom@150: terom@150: try : terom@150: return _lookup.get_template("%s.%s" % (name, TEMPLATE_EXT)) terom@150: terom@150: except : terom@150: raise TemplateError("Template broken: %r" % (name, ), status='500 Internal Server Error', details=exceptions.text_error_template().render()) terom@150: terom@150: def load (path) : terom@150: """ terom@150: Loads a template from a specific file terom@150: """ terom@150: terom@150: try : terom@150: return Template(filename=path, module_directory=CACHE_DIR) terom@150: terom@150: except : terom@150: raise TemplateError("Template broken: %r" % (path, ), status='500 Internal Server Error', details=exceptions.text_error_template().render()) terom@150: terom@150: def render_template (tpl, **params) : terom@150: """ terom@150: Render the given template, returning the output, or raising a TemplateError terom@150: """ terom@150: terom@150: try : terom@150: return tpl.render(**params) terom@153: terom@153: # a template may render other templates terom@153: except TemplateError : terom@153: raise terom@150: terom@150: except : terom@153: details = exceptions.text_error_template().render() terom@153: terom@153: raise TemplateError("Template render failed", status='500 Internal Server Error', details=details) terom@150: terom@150: def render (name, **params) : terom@150: """ terom@150: Render a template, using lookup() on the given name terom@150: """ terom@150: terom@150: return render_template(lookup(name), **params) terom@150: terom@150: def render_file (path, **params) : terom@150: """ terom@150: Render a template, using load() on the given path terom@150: """ terom@150: terom@150: return render_template(load(path), **params) terom@150: