The Badger Book
The Badger Book

The Template Toolkit

The Template Toolkit (TT) is a fast, flexible and highly extensible template processing system. Released under an Open Source licence, it is free (in both senses: cost and liberty) for anyone and everyone to use. It is most often employed to generate HTML pages for web sites ranging from the very small to the very large. It also has a wide range of applications in other text processing areas: creating form letters (e.g. a "mailshot"), data files (e.g. XML files, RSS feeds, etc.), configuration files, and so on. It can even be used to generate and manipulate images (GIF, PNG, etc).

The Template Toolkit is stable, mature, widely used, and has an active developer and user community. There's an O'Reilly book dedicated to it (the "Badger Book") written by Darren Chamberlain, Dave Cross and myself.

Modular Web Site Construction

Top Close Open

The Template Toolkit allows you to generate the pages for your web site (or whatever it is you're building) in a modular fashion. Instead of laboriously cut-and-pasting the markup for the "boilerplate" elements of a web site into each page, the Template Toolkit encourages you to move your headers, footers, menus and so on into separate files. These template components can then be used and reused on each and every page on your site with a simple directive embedded in the page wherever and whenever you want them.

Here's an example of a template for a basic web page.

[% INCLUDE header title="Hello World" %]
<p>
  Welcome to my web page!
</p>
[% INCLUDE footer copyright="Me, 2006" %]

Directive are indicated by the [% ... %] markers and contain instructions for the Template Toolkit. In this case the INCLUDE directive is an instruction to process the named template component (e.g. header) using the variable definitions that follow (e.g. title="Hello World"). When TT processes a template it performs the actions associated with each directive and inserts the results generated into the output document in place of the original directive tag. All other text is passed through untouched. In other words, TT fills in the "blanks" in your template.

Here's what our header and footer templates might look like:

header

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>[% title %]</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
  </head>
  <body> 
    <div id="header">
     [% INCLUDE logo %]
     [% INCLUDE menu %]
    </div>

footer

    <div id="footer">
     [% INCLUDE links %]
     <div id="copyright">
       [% copyright %]
     </div>
    </div>
  </body>
</html>

Notice where the [% title %] variable appears in the header and [% copyright %] in the footer. These are the simplest kind of directives that insert the value of the named variables (technically speaking they're GET directives, but the GET keyword is usually dropped for clarity). In this case we're providing the values for title and copyright when we INCLUDE the header and footer template components respectively. TT also allows you to define global variables to save you having to pass lots of data around each time you use a component. You can also define and manipulate complex data structures (lists and hash arrays) and call Perl subroutines and object methods.

Inserting the value of variable is just one thing you can do. In these examples our components go on to INCLUDE other templates, which themselves can go on to INCLUDE other templates, and so on. There's a whole range of other directives to perform loops (FOREACH, WHILE), conditional tests (IF, ELSIF, UNLESS, etc), load plugins (USE), and filter text (FILTER), to name just a few.

Benefits of this Approach

Top Close Open

There are a number of immediate benefits to the modular approach that TT affords. First, it becomes easier to add a new page to a web site. Simply take your basic page content and call upon your library of components to add the user interface elements and other eye-candy. As well as making life easy, it also ensures that all your pages end up with a consistent look and feel.

The second benefit is that these pages are now easier to subsequently update. All the extra header and footer cruft that previously obscured the core content has been moved out and replaced by simple INCLUDE directives. In fact, you can even get rid of those as well by providing TT with the name of one or more templates that you want automatically added to the top (e.g. header) and bottom (e.g. footer) of each page it processes (via the PRE_PROCESS and POST_PROCESS configuration options.

The third major benefit comes when you want to change the header, footer, menu or some other component. Instead of wading through every single page to make the edit, you now only have to change that one component file and have TT regenerate your pages to glue the new element into place. Tedious and error-prone site updates that used to take hours or even days can now be done in seconds. Take that to the extreme and you can build a fully skinable, customisable, localisable and generally flexible web site that is easy to maintain and manage.

Plugins for Everything

Top Close Open

The Template Toolkit is written in the Perl programming language and draws on the vast repository of Perl modules available from CPAN that allow you to do pretty much anything you can imagine. Want to access a database from your templates? Easy - there's a plugin that uses Perl's excellent DBI module for low-level database operations (e.g. direct queries) and another which uses Class::DBI for mapping database records to objects. Need to manipulate some XML files? No problem - there are specific plugins implementing the XML DOM and XPath standards, and a more general plugin interfacing direct to libxml which does it all. Want to generate new images on-the-fly or re-colour existing images to theme your web site user interface? Easy peasy, lemon squeezy.

If there isn't an existing plugin that does what you want then you can write your own. You don't need to know anything much about Perl to use the Template Toolkit but it's there if you want to extend it. In many cases, writing a new TT plugin requires little more than a half dozen lines of fairly basic Perl code and there are plenty of examples for you to base your code on. Perl isn't everyone's favourite language but the code for TT is generally clean and comprehensible (at least in the parts that users typically interface with, such as writing extension plugins). If you don't already know Perl then there are plenty of excellent resources available online and onshelf to help you learn it. Or if you just want to find someone else to solve the problem for you then you won't have to swing a cat far to find someone with Perl programming skills on their CV.

Find Out More

Top Close Open

The Template Toolkit is available from CPAN. It is provided with comprehensive documentation covering its use, features, directives, configuration options and related matters.

The Template Toolkit web site has further information on fetching, installing, using and abusing TT. It also has online versions of the core documentation.

The Badger Book contains updated and extended documentation, tutorials, hundreds of examples, code walk-throughs and various other goodies. It has chapters dedicated to building web sites, using databases, manipulating XML files and extending the Template Toolkit. It also has a badger on the front cover which surely makes it worth the money by itself!

You may also like to take a look at another article on this site which talks more about the Separation of Concerns that TT gives you and why it's a Good Thing.