lib/template.py
author Tero Marttila <terom@fixme.fi>
Fri, 06 Feb 2009 22:48:00 +0200
changeset 8 0ce1f471e9d7
child 11 fa216534ae45
permissions -rw-r--r--
and it works, a lot better than before
"""
    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)