"""
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)
# a template may render other templates
except TemplateError :
raise
except :
details = exceptions.text_error_template().render()
raise TemplateError("Template render failed", status='500 Internal Server Error', details=details)
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)