Home arrow Perl Programming arrow Page 7 - Getting Started with the Perl Template Toolkit

The Template Toolkit Language - Perl

This chapter compares the Template Toolkit to other templating systems such as HTML::Mason and HTML::Template, describes how to install it, then shows you what templates look like and how to process them. (From the book, Perl Template Toolkit, O'Reilly Media, ISBN: 0596004761, by Darren Chamberlain, Dave Cross and Andy Wardley.)

  1. Getting Started with the Perl Template Toolkit
  2. The Templating Ecosystem
  3. Installing the Template Toolkit
  4. Documentation and Support
  5. Using the Template Toolkit
  6. The Template Module
  7. The Template Toolkit Language
  8. Dynamic Variables
  9. Template Processing Directives
  10. Integrating and Extending the Template Toolkit
By: O'Reilly Media
Rating: starstarstarstarstar / 23
July 28, 2004

print this article



The Template Toolkit language is a presentation language rather than a general-purpose programming language. It provides the kind of features that you would expect to see in a regular programming language, including loops, conditional tests, and the ability to manipulate variable values. However, in this case they serve a slightly different purpose. The Template Toolkit is designed for the task of generating content and presenting data, and it generally leaves more complex issues to a real programming language, namely, Perl.

We have already seen the basics of what a template looks like—a mixture of tags (known as directives) and other fixed text. The template processor interprets the directives and the remaining text is passed through unchanged.

By default, the start and end of a directive are marked by the sequences [% and %], but the TAGS directive can be used to change them if you don’t like these. The TAGS directive takes either one or two arguments. The single-argument version expects the name of a predefined tag set. For example, the star set replaces the tag delimiters with [* and *]:

[% TAGS star %]
People of [* planet *], your attention please.

If you give TAGS two arguments, they define the start and end tag markers that you want to use. For example, if you’re processing plain text, you might find something like this more lightweight and easier to type:

[% TAGS { } %]
People of {planet}, your attention please.

Or if you are processing HTML and you prefer an HTML style, how about this:

[% TAGS<tt: > %]
<p>People of <tt:planet>, your attention please.

Changes to tags take effect immediately and affect only the current file.

You can also set these from the command line with ttree by using the --start_tag, --end_tag, and --tag_style options. From a Perl script, the corresponding configuration options for the Template module are START_TAG, END_TAG, and TAG_STYLE. For Apache::Template, the TT2Tags option can be used with one or two arguments, as per the TAGS directive.

In the rest of this book, we use the default tag style. We like it because it makes the directives stand out from the surrounding text, rather than making them blend in. We think it makes templates easier to read and write when you can more clearly distinguish one part from another.

Template Variables

The variables that we have used so far have been scalar variables. A scalar variable stores a single piece of information—either a string or a number.

The value of a scalar variable is inserted in a template by using the variable name inside a directive like this:

[% planet %]

A variable wouldn’t be worthy of the name if you couldn’t also set its value. We have seen examples of doing this using the --define option of the tpage command, but it is also possible to set a variable’s value inside a template:

[% planet = 'Magrethea' %]
People of [% planet % ], your attention please.

Complex Variables

In addition to scalar variables, the Template Toolkit also supports two complex data types for storing multiple values: the list and hash array (also known as a hash). A list is an ordered array of other variables, indexed numerically and starting at element 0. A hash is an unordered collection of other variables, which are indexed and accessible by a unique name or key.

Perl programmers will already be familiar with these data structures. When you use the Template Toolkit from Perl you can easily define hash arrays and lists that are then passed as template variables to the process( ) method.

Example 1-9 shows a Perl program similar to Example 1-6, which defines a list of friends and a hash of terms as template variables.

use Template;

my $tt = Template->new();
my $input = 'friends.tt';
my $vars = {
      friends => [ 'Ford Prefect', 'Slartibartfast' ],
      terms => {
          sass => 'know, be aware of, meet, have sex with',
          hoopy => 'really together guy',
          frood => 'really, amazingly together guy',

$tt->process($input, $vars)
     || die $tt->error();

Example 1-9. Perl program to process friends.tt

Example 1-10 is the friends.tt template that Example 1-9 processes.

Your friends are:
[% FOREACH friend IN friends -%]
 * [% friend %]
[% END -%]

You know the following terms:
[% FOREACH term IN terms.keys.sort -%]
   [% term %]: [% terms.$term %]
[% END -%]

Example 1-10. The friends.tt template

This is the output generated by Example 1-9:

Your friends are:
* Ford Prefect
* Slartibartfast

You know the following terms:
frood: really, amazingly together guy
hoopy: really together guy
sass: know, be aware of, meet, have sex with

There will be times when you’re using the Template Toolkit with tpage or ttree and don’t want to have to write a Perl program, however simple, just to use some complex variables. The Template Toolkit allows you to define lists and hash data structures inside templates, using syntax similar (or identical if you prefer) to the Perl equivalents shown earlier.

The simple examples in the sections that follow should give you a flavor of how lists and hash data structures are defined and used in templates. Chapter 3 describes the Template Toolkit language in detail, showing the different variations in syntax that are permitted to satisfy both Perl programmers (who expect => to be used to separate a hash key from a value, for example) and HTML designers (who probably don’t know any different and are just as happy using the simpler =).


A list variable is defined in a template using the [...] construct. Here’s how we would create the equivalent of the friends list from Example 1-9:

[% friends = [ 'Ford Prefect', 'Slartibartfast' ] %]

List elements are accessed using the dot operator (.). Follow the list name with a dot and then the element number, starting at zero for the first element:

[% friends.0 %]         # Ford Prefect
[% friends.1 %]         # Slartibartfast

It is also possible to access elements from the list using a variable containing an index value. Simply prefix the variable with a $ character:

[% index = 1 %]
[% friends.$index %]    # Slartibartfast


A hash is defined in a template using the {...} construct:

[% terms = { 
     sass  = 'know, be aware of, meet, have sex with' 
     hoopy = 'really together guy' 
     frood = 'really, amazingly together guy' 

Each pair of items within the { and } is composed of the key, to the left of the = (or => if you prefer), and the value to the right. Separate pairs of items with commas, although it’s not obligatory. Here is the same template written in a Perlish style:

[% terms => {
   sass  => 'know, be aware of, meet, have sex with', 
   hoopy => 'really together guy', 
   frood => 'really, amazingly together guy', 

Hash items are also accessed using the dot operator. In this case, the key for the required item is specified after the dot character:

[% terms.hoopy %]     # really together guy

You can also access hash items using a variable that contains a key. Again, the variable name should be prefixed with a $ character:

[% key = 'frood' %]
[% terms.$key %]      # really, amazingly together guy

Nesting list and hash definitions

Lists and hashes can be nested inside each other to create complex data structures:

[% arthur = { 
    name = 'Arthur Dent', 
    planet = 'Earth', 
    friends = [ 
      { name = 'Ford Prefect' 
        home = 'Betelgeuse' 
        type = 'frood' } 
      { name = 'Slartibartfast' 
        home = 'Magrethea' 
        type = 'hoopy' } 
    terms = { 
     sass  = 'know, be aware of, meet, have sex with' 
     hoopy = 'really together guy' 
     frood = 'really, amazingly together guy' 


You can access items buried deep within a nested data structure by chaining together a series of dot operations to create a compound variable:

[% arthur.friends.1.name %] # Slartibartfast

The Template Toolkit works out which dot operators are performing hash lookups (friends and name) and which are performing list lookups (1), and then automatically does the right thing to return the correct value. Comparing this to the equivalent Perl code, the Template Toolkit’s uniform dot operator makes things much clearer:

# TT

# Perl

This illustrates one of the key benefits of using a presentation language like the Template Toolkit for generating content, rather than a programming language such as Perl.* When you write a program using a real programming language such as Perl, it’s important to know which variables are scalars and which are lists, hashes, subroutines, objects, and so on. It’s also critical that you use exactly the right kind of syntax relevant to each data type. Otherwise, your program might try to do something that it shouldn’t, possibly corrupting the data, causing the program to exit with an error, or even failing to compile and run in the first place.

(Note: *Which of course, we still rely on a great deal, not only as the language in which the Template Toolkit is written, but also as the means by which you can extend it and add your own custom functionality to your templates, as we will see in the next section.)

However, when you’re writing templates to present your data as HTML pages, or in some other output format, these issues are of less concern. You’re far more interested in how the data is going to be laid out, than in how it is stored or calculated on demand by the underlying Perl code (as we see in the next section). As long as the value for a user’s name, for example, is inserted in the right place in the template when we ask for arthur.friends.1.name, we’re happy. By the time the data is presented as output in a template, it is all text anyway.

You can also used dotted variables as hash keys to reference other variables. The following example shows how this is done using ${ ... } to explicitly scope the range of the second variable name:

[% arthur.terms.${arthur.friends.1.type} %]

The arthur.friends.1.type variable returns the value hoopy, resulting in a final expression equivalent to arthur.terms.hoopy. This ultimately provides us with the value really together guy.

You can use a temporary variable to break this down into smaller pieces. For example:

[%friend = arthur.friends.1-%]
[%friend.name%] is a [%arthur.terms.${friend.type}%].

This generates the following output:

Slartibartfast is a really together guy.


Buy the book!If you've enjoyed what you've seen here, or to get more information, click on the "Buy the book!" graphic. Pick up a copy today!

Visit the O'Reilly Network http://www.oreillynet.com for more online content.

>>> More Perl Programming Articles          >>> More By O'Reilly Media

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: