The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

INTRODUCTION

The Template Toolkit is a set of Perl modules which collectively implement a template processing system. In this context, a template is a text document containing special markup tags called 'directives'. A directive is an instruction for the template processor to perform some action and substitute the result into the document in place of the original directive. Directives include those to define or insert a variable value, iterate through a list of values (FOREACH), declare a conditional block (IF/UNLESS/ELSE), include and process another template file (INCLUDE) and so on.

In all other respects, the document is a plain text file and may contain any other content (e.g. HTML, XML, RTF, LaTeX, etc). Directives are inserted in the document within the special markup tags which are '[%' and '%]' by default, but can be changed via the module configuration options. Here's an example of an HTML document with additional Template Toolkit directives.

   [% INCLUDE header
      title = 'This is an HTML example'
   %]

   <h1>Some Interesting Links</h1>

   [% webpages = [
         { url => 'http://foo.org', title => 'The Foo Organsiation' }
         { url => 'http://bar.org', title => 'The Bar Organsiation' }
      ]
   %]

   Links:
   <ul>
   [% FOREACH link = webpages %]
      <li><a href="[% link.url %]">[% link.title %]</a>
   [% END %]
   </ul>

   [% INCLUDE footer %]

This example shows how the INCLUDE directive is used to load and process separate 'header' and 'footer' template files, including the output in the current document. These files might look like this:

header: <html> <head> <title>[% title %]</title> </head>

    <body bgcolor="#ffffff">

footer: <hr>

    <center>
    &copy; Copyright 2000 Me, Myself, I
    </center>

    </body>
    </html>

The example also uses the FOREACH directive to iterate through the 'webpages' list to build a table of links. In this example, we have defined this list within the template to contain a number of hash references, each containing a 'url' and 'title' member. The FOREACH directive iterates through the list, aliasing 'link' to each item (hash ref). The [% link.url %] and [% link.title %] directives then access the individual values in the hash and insert them into the document.

The following sections show other ways in which data can be defined for use in a template.