Template Toolkit is Too Cool

The Perl Journal May, 2004


Ilove tools that seem to do their work magically. You know the ones I mean—those that just make all the right assumptions about what you want. The Template Toolkit (http://template-toolkit.org/) is one such tool. It's an extraordinarily popular system, so it's a good bet you already know about it. But that won't deter me from singing its praises. The Template Toolkit (TT) is, well, a templating mechanism. At its simplest, it can be used like this:

use Template;
$var = {
  greeting => 'Hello',
};
$tt = Template->new();
$tt->process("mytemplate.tt", $var);

where "mytemplate.tt" is a template file. This code writes the contents of mytemplate.tt to STDOUT, replacing any [% greeting %] template directives with the string "Hello."

Of course, instead of $var in this example, you could pass in just about anything in your code, including object references. This is a godsend. Hash elements and array elements can be accessed in template directives with a simple dot notation, such as [% foo.0.bar.1%].

You can almost forget about how your data will need to be formatted on output. Just store your data in a place where you can get to it easily, build your templates wisely, and TT will take care of the rest.

TT also provides some built-in functions (or filters, in TT parlance) that let you munge your output data in lots of useful ways. You can even write your own filters. Taken together, all the parts of TT represent an entire language for writing templates, complete with if statements and looping constructs. It's so rich, in fact, that it's tempting to offload much of your data processing to your templates, which can make for messy templates. Like any good Perl tool, TT doesn't dictate where that balance should lie—it leaves up to you the decision of whether or not to get carried away.

Another, less obvious virtue is that TT promotes good design. While templating in general is good practice because it separates data from presentation, and allows your applications to be more easily customized by users, TT's particular brand of template mechanism goes a step further and promotes good object design. The cleaner and more sensibly designed your data structures are, the easier they are to reference with TT directives. To simplify my own TT directives, I have frequently gone back to the drawing board and come up with a better way of internally representing data. It's an example of good form promoting good form.

If you haven't looked at the Template Toolkit, do yourself a favor and try it out. I guarantee you'll find a use for it.

Kevin Carlson
Executive Editor
The Perl Journal