Template Toolkit - Now With Added Python Goodness!
Sunday, 10 February 2008
I had some idiosyncratic learning experiences lately. I read something about two things I want to learn about and suddenly, without explicitly searching for it, stumble upon something that deals with both of them. This happened again this morning. The two things that I was already learning were Python and the Template Toolkit.
As a Python novice, I just threw a first glance at the Vaults of Parnassus and had to stop browsing when I came across Cheetah. They dont’t merely call it ‘a Python-Powered Template Engine’ but ‘The Python-Powered Template Engine’. THE. What a bold statement.
As a Perl hacker for some years I had, of course, quite some encounters with CPAN. While I consider CPAN one of Perl’s strengths in general, the community approach to libraries has some downsides, especially in consideration of Perl’s TMTOWTDI mantra. For very special tasks, there may not even be a CPAN module at all, but for most common tasks, there’s more than one. Sometimes there are multiple full-blown alternatives for getting some particular job done.
One task that tends to attract a multitude of solutions is template processing. There are minimalist approches, consisting of single modules, as well as entire hierarchies of modules, just like Template Toolkit. After using HTML::Template for some times, I am an excited Template Toolkit apprentice, especially admiring the flexibility.
So when I read the THE-brag about Cheetah, I was first skeptical, but I also thought that maybe Cheetah might indeed be for Python what Template Toolkit was for Perl. I ran a google search for ‘template toolkit python’ to find out if someone confirmed that Cheetah was the thing to use that most closely resembles Template Toolkit.
And guess what? There’s a python port of Template Toolkit and it’s even hosted at template-toolkit.org. Here’s a simplistic example in both Perl and Python.
First, the template.
[% greeting %]
Second, the Perl code to print out a well-known message.
use strict;
use Template;
my $template = Template->new();
$template->process(’001_hello_world.tt’, { greeting => ‘Hello, World!’ });
Third, the corresponding code to do the same stuff in Python.
from template import Template
template = Template()
print template.process(’001_hello_world.tt’, { ‘greeting’ : ‘Hello, World!’ })
A Short History of Nearly Everything
Seven Languages in Seven Weeks
I Am a Strange Loop