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