Skip to main content

Ralsina.Me — Roberto Alsina's website

Rawdog is flexible: using Mako templates

I am us­ing raw­dog for Plan­e­ta PyAr and I am very hap­py with it. One thing I re­al­ly did­n't like was the tem­plat­ing.

Why? It's ba­si­cal­ly un­doc­u­ment­ed, it looks ug­ly and it does­n't sup­port tem­plate in­her­i­tance, which in this case is very use­ful, be­cause I am ac­tu­al­ly do­ing two very sim­i­lar plan­et­s: 1 2.

So, since I saw a plug­in to use Vel­lum tem­plates, which means the tem­plat­ing is plug­gable, why not use my favourite tem­plat­ing li­brary (Mako) in­stead?

It turns out to be very easy to do!

Just put this in your plug­ins fold­er and start us­ing Mako tem­plates (yes, the plan­et's con­fig and stuff is in github. Why not?).

# -*- coding: utf-8 -*-
import rawdoglib.plugins

from mako.template import Template
from mako.lookup import TemplateLookup
from mako import exceptions

class MakoPlugin:
    def __init__(self):
        self.lookup = TemplateLookup(directories=['.'],\
                              output_encoding='utf-8',\
                              encoding_errors='replace')

    def fill_template(self,template, bits, result):
        self.lookup.put_string('actual',template)
        t=self.lookup.get_template('actual')
        try:
            r=t.render_unicode(**bits)
        except:
            r=exceptions.html_error_template().render()
        result.value=r
        return False

p = MakoPlugin()
rawdoglib.plugins.attach_hook("fill_template",\
                              p.fill_template)

Yup, 20 lines of code!


Contents © 2000-2024 Roberto Alsina