Using Cheetah together with Colubrid

There are two decorators for using kid from within Colubrid: a cached and an uncached version.

Uncached

import os
from colubrid import HttpResponse
from Cheetah.Compiler import Compiler

searchpath = 'templates'

def render(name):
    path = os.path.join(searchpath, '%s.tmpl' % name)
    def proxy(f):
        def on_call(*args, **kwargs):
            c = f(*args, **kwargs) or {}
            text = file(path).read()
            c = Compiler(source=text, mainClassName='GenTemplate')
            code = str(c)
            ns = {}
            exec code in ns
            t = ns['GenTemplate']()
            for key, value in c.iteritems():
                setattr(t, key, value)
            return HttpResponse(str(t))
        return on_call
    return proxy

Cached

import os
from colubrid.request import Request
from Cheetah.Compiler import Compiler

searchpath = 'templates'

def render(name):
    path = os.path.join(searchpath, '%s.tmpl' % name)
    text = file(path).read()
    c = Compiler(source=text, mainClassName='GenTemplate')
    code = str(c)
    ns = {}
    exec code in ns
    tmpl = ns['GenTemplate']
    def proxy(f):
        def on_call(*args, **kwargs):
            c = f(*args, **kwargs) or {}
            t = tmpl()
            for key, value in c.iteritems():
                setattr(t, key, value)
            return HttpResponse(str(t))
        return on_call
    return proxy

Usage

You can use it from any Colubrid application type:

from colubrid import RegexApplication, execute
import time

class MyApplication(RegexApplication):
    urls = [
        (r'^index$', 'index')
    ]

    @render('index')
    def index(self):
        return {
            'now': time.time()
        }

app = MyApplication

if __name__ == '__main__':
    execute()

Example Template

Here the index.tmpl template from the example above:

<h1>Welcome from the Index</h1>

The current Unix Timestamp is $now
Last Change: 10 Sep 2006 17:12:26 | show source