Using Jinja together with Colubrid

You can easily use Jinja with Colubrid. There are two decorators available.

A cached and an uncached one. While developing you should use the uncached decorator because it doesn't require to restart the application server.

Uncached

This is an uncached version of an templating decorator:

from colubrid import HttpResponse
from jinja import Template, Context, FileSystemLoader

loader = FileSystemLoader('templates/')

def render(name):
    def proxy(f):
        def on_call(*args, **kwargs):
            result = f(*args, **kwargs)
            if isinstance(result, dict):
                c = Context(result)
            else:
                c = Context()
            t = Template(name, loader)
            return HttpResponse(t.render(c))
        return on_call
    return proxy

Cached

And here a cached one:

from colubrid import HttpResponse
from jinja import Template, Context, CachedFileSystemLoader

loader = CachedFileSystemLoader('templates/')

def render(name):
    def proxy(f):
        t = Template(name, loader)
        def on_call(*args, **kwargs):
            result = f(*args, **kwargs)
            if isinstance(result, dict):
                c = Context(result)
            else:
                c = Context()
            return HttpResponse(t.render(c))
        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:

<h1>Welcome from the Index</h1>

The current Unix Timestamp is {{ now }}.
Last Change: 23 Apr 2006 18:55:42 | show source