Using simpleTAL together with Colubrid

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

Uncached

import os
from colubrid import HttpResponse
from simpletal import simpleTAL, simpleTALES
from cStringIO import StringIO

searchpath = 'templates'

def render(name):
    path = os.path.join(searchpath, '%s.html' % name)
    def proxy(f):
        def on_call(*args, **kwargs):
            c = f(*args, **kwargs) or {}
            context = simpleTALES.Context()
            for key, value in c.iteritems():
                context.addGlobal(key, value)
            out = StringIO()
            fp = file(path)
            template = simpleTAL.compileHTMLTemplate(fp)
            fp.close()
            template.expand(context, out)
            return HttpResponse(out.getvalue())
        return on_call
    return proxy

Cached

import os
from colubrid import HttpResponse
from simpletal import simpleTAL, simpleTALES
from cStringIO import StringIO

searchpath = 'templates'

def render(name):
    path = os.path.join(searchpath, '%s.html' % name)
    fp = file(path)
    template = simpleTAL.compileHTMLTemplate(fp)
    fp.close()
    def proxy(f):
        def on_call(*args, **kwargs):
            c = f(*args, **kwargs) or {}
            context = simpleTALES.Context()
            for key, value in c.iteritems():
                context.addGlobal(key, value)
            out = StringIO()
            template.expand(context, out)
            return HttpResponse(out.getvalue())
        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.html template from the example above:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <h1>Welcome from the Index Page</h1>

    The current Unix Timestamp is <span tal:replace="now">timestamp</span>
</body>
</html>
Last Change: 10 Sep 2006 17:12:26 | show source