CherryPy Project Download

Here's a simple Tool for Mako templating:

import cherrypy
from mako.lookup import TemplateLookup

class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
    """Callable which sets response.body."""
    def __init__(self, template, next_handler):
        self.template = template
        self.next_handler = next_handler
    def __call__(self):
        env = globals().copy()
        return self.template.render(**env)

class MakoLoader(object):
    def __init__(self):
        self.lookups = {}
    def __call__(self, filename, directories, module_directory=None,
        # Find the appropriate template lookup.
        key = (tuple(directories), module_directory)
            lookup = self.lookups[key]
        except KeyError:
            lookup = TemplateLookup(directories=directories,
            self.lookups[key] = lookup
        cherrypy.request.lookup = lookup
        # Replace the current handler.
        cherrypy.request.template = t = lookup.get_template(filename)
        cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler)

main = MakoLoader() = cherrypy.Tool('on_start_resource', main)

Use it like this:

def index(name=None):
    return {'username': name}

You will also need two config options:

tools.mako.collection_size = 500
tools.mako.directories = "path/to/templates"


Hello, ${username}!

To avoid UTF-8 encoding problems use following for template lookup

lookup = TemplateLookup(directories=directories, module_directory=module_directory, collection_size=collection_size,output_encoding='utf-8', encoding_errors='replace')

Hosted by WebFaction

Log in as guest/cherrypy to create/edit wiki pages