24th



NAME

Template Toolkit - a fast, flexible and extensible template processing system


SYNOPSIS

  use Template;
  # some useful options (see below for full list)
  my $config = {
      INCLUDE_PATH => '/search/path',  # or list ref
      INTERPOLATE  => 1,               # expand "$var" in plain text
      POST_CHOMP   => 1,               # cleanup whitespace 
      PRE_PROCESS  => 'header',        # prefix each template
      EVAL_PERL    => 1,               # evaluate Perl code blocks
  };
  # create Template object
  my $template = Template->new($config);
  # define template variables for replacement
  my $vars = {
      var1  => $value,
      var2  => \%hash,
      var3  => \@list,
      var4  => \&code,
      var5  => $object,
  };
  # specify input filename, or file handle, text reference, etc.
  my $input = 'myfile.html';
  # process input template, substituting variables
  $template->process($input, $vars)
      || die $template->error();


SUMMARY OF TEMPLATE DIRECTIVES

  GET       - evaluate and print a variable or value
              [%   GET variable %]    # 'GET' keyword is optional
              [%       variable %]
              [%       hash.key %]
              [%         list.n %]
              [%     code(args) %]
              [% obj.meth(args) %]
              [%  "value: $var" %]
  CALL      - as above without printing result (e.g. call code)
              [%  CALL variable %]
  SET       - assign a value to a variable
              [% SET variable = value %]    # 'SET' also optional
              [%     variable = other_variable
                     variable = 'literal text @ $100'
                     variable = "interpolated text: $var"
                     list     = [ val, val, val, val, ... ]
                     list     = [ val..val ]
                     hash     = { var => val, var => val, ... }
              %]
  DEFAULT   - as SET above, if variable(s) not set
              [% DEFAULT variable = value %]
  INSERT    - insert a file without any processing
              [% INSERT legalese.txt %]
  INCLUDE   - process another template file/block, localising vars
              [% INCLUDE template %]
              [% INCLUDE template  var = val, ... %]
  PROCESS   - as above, without localising variables
              [% PROCESS template %]
              [% PROCESS template  var = val, ... %]
  WRAPPER   - process a template to enclose specified block
              [% WRAPPER template %]
                 content
              [% END %]
  BLOCK     - define a named template block for INCLUDE, etc.
              [% BLOCK template %]
                 content
              [% END %]
  FOREACH   - repeat block for each value in a list
              [% FOREACH variable = [ val, val, val ] %]
              [% FOREACH variable = list %]
              [% FOREACH list %]
                 content...
                 [% variable %]
              [% END %]
  WHILE     - iterate while condition is true
              [% WHILE condition %]
                 content
              [% END %]
  IF / UNLESS / ELSIF / ELSE
            - process block if condition is true/false.
              [% IF condition %]
                 content
              [% ELSIF condition %]
                 content
              [% ELSE %]
                 content
              [% END %]
              [% UNLESS condition %]
                 content
              [% # ELSIF/ELSE as per IF, above %]
                 content
              [% END %]
  SWITCH / CASE
            - multi-way switch/case statement
              [% SWITCH variable %]
              [% CASE val1 %]
                 content
              [% CASE [ val2, val3 ] %]
                 content
              [% CASE %]         # or [% CASE DEFAULT %]
                 content
              [% END %]
  MACRO     - create a named macro for some other directive or block
              [% MACRO name <directive> %]
              [% MACRO name(arg1, arg2) <directive> %]
              ...
              [% name %]
              [% name(val1, val2) %]
  FILTER    - post-process block through a filter
              [% FILTER name %]
              [% FILTER name( params ) %]
              [% FILTER alias = name( params ) %]
                 content
              [% END %]
  USE       - load a "plugin" module (or any regular Perl module 
              with LOAD_PERL option)
              [% USE name %]
              [% USE name( params ) %] 
              [% USE var = name( params ) %]
              ...
              [% name.method %]
              [% var.method %]
  PERL / RAWPERL
            - evaluate blocks of Perl code (requires EVAL_PERL option)
              [% PERL %]
                 # perl code goes here
                 $stash->set('foo', 10);
                 print "set 'foo' to ", $stash->get('foo'), "\n";
                 print $context->include('footer', { var => $val });
              [% END %]
              [% RAWPERL %]
                 # raw perl code goes here, no magic but fast.
                 $output .= 'some output';
              [% END %]
  TRY / THROW / CATCH / FINAL
            - exception handling
              [% TRY %]
                 content
                 [% THROW type info %]
              [% CATCH type %]
                 catch content
                 [% error.type %] [% error.info %]
              [% CATCH %]       # or [% CATCH DEFAULT %]
                 content
              [% FINAL %]
                 this block is always processed
              [% END %]
  NEXT      - next item in a FOREACH/WHILE loop
              [% NEXT %]

  LAST      - break out of FOREACH/WHILE loop
              [% LAST %]

  RETURN    - stop processing current template
              [% RETURN %]
  STOP      - stop processing all templates and return to caller
              [% STOP %]
  COMMENT   - ignored and deleted
              [% # this is a comment to the end of line
                 foo = 'bar'
              %]
              [%# placing the '#' immediately inside the directive
                  tag comments out the entire directive
              %]
  TAGS      - define new tag style or characters (default: [% %])
              [% TAGS html %]
              [% TAGS <!-- --> %]


VERSION

This is version 2.00-rc2 of the Template Toolkit.

Please consult the Changes file for information about visible changes in the Template Toolkit between releases. The TODO file contains details of known bugs, planned enhancements, features, fixes, etc.

The latest version of the Template Toolkit can be downloaded from any CPAN site in the directory:

    /modules/by-module/Template/

For a list of CPAN sites, see:

    http://www.cpan.org/

Information regarding interim and development versions is posted to the templates mailing list and available from the Template Toolkit web site:

    http://www.template-toolkit.org/


DESCRIPTION

The Template Toolkit is a collection of modules which implement a fast, flexible, powerful and extensible template processing system. It was originally designed and remains primarily useful for generating dynamic web content, but it can be used equally well for processing any kind of text documents. This POD documentation is all generated using the Template Toolkit batch mode utility ttree, for example.

At the simplest level it provides an easy way to process template files, filling in embedded variable references with their equivalent values.

    Dear [% name %],
    It has come to our attention that your account is in 
    arrears to the sum of [% debt %].
    Please settle your account before [% deadline %] or we 
    will be forced to revoke your Licence to Thrill.
    The Management.

By default, template directives are embedded within the character sequences '[%' ... '%]' but you can change these and various other options to configure how the Template Toolkit looks, feels and works. You can set the INTERPOLATE option, for example, if you prefer to embed your variables in Perl style:

    Dear $name,
    It has come to our attention that your account is in 
    arrears to the sum of $debt.
    ...

The Template.pm module is the front end to the Template Toolkit, providing access to the full range of functionality through a single module with a simple interface. It loads the other modules as required and instantiates a default set of objects to handle subsequent template processing requests. Configuration parameters may be passed to the Template.pm constructor, new(), which are then used to configure the underlying objects.

    use Template;
    my $tt = Template->new({
        INCLUDE_PATH => '/usr/local/templates',
        INTERPOLATE  => 1,
    }) || die "$Template::ERROR\n";

The Template object implements a process() method for processing template files or text. The name of the input template (or various other sources) is passed as the first argument, followed by a reference to a hash array of variable definitions for substitution in the template.

    my $vars = {
        name     => 'Count Edward van Halen',
        debt     => '3 riffs and a solo',
        deadline => 'the next chorus',
    };
    $template->process('letters/overdrawn', $vars)
        || die $template->error(), "\n";

The process() method returns true (1) on success and prints the template output to STDOUT, by default. On error, the process() method returns false (undef). The error() method can then be called to retrieve details of the error.

A number of special directives are provided, such as INSERT, INCLUDE and PROCESS, which allow content to be built up from smaller template components. This permits a modular approach to building a web site or other content repository, promoting reusability, cross-site consistency, ease of construction and subsequent maintenance. Common elements such as headers, footers, menu bars, tables, and so on, can be created as separate template files which can then be processed into other documents as required. All defined variables are inherited by these templates along with any additional ``local'' values specified.

    [% PROCESS header 
         title = "The Cat Sat on the Mat"
    %]
    [% PROCESS menu %]
    The location of the missing feline has now been established.
    Thank you for your assistance.
    [% INSERT legal/disclaimer %]
    [% PROCESS footer %]

You can also define a template as a BLOCK within the same file and PROCESS it just like any other template file. This can be invaluable for building up repetitive elements such as tables, menus, etc.

    [% BLOCK tabrow %]
       <tr><td>[% name %]</td><td>[% email %]</td></tr>
    [% END %]
    <table>
    [% PROCESS tabrow name="tom"   email="tom@here.org"    %]
    [% PROCESS tabrow name="dick"  email="disk@there.org"  %]
    [% PROCESS tabrow name="larry" email="larry@where.org" %]
    </table>

One of the key features that sets the Template Toolkit apart from other template processors is the ability to bind template variables to any kind of Perl data: scalars, lists, hash arrays, sub-routines and objects.

    my $vars = {
        root   => 'http://here.com/there',
        menu   => [ 'modules', 'authors', 'scripts' ],
        client => {
            name => 'Doctor Joseph von Satriani',
            id   => 'JVSAT',
        },
        checkout => sub { my $total = shift; ...; return $something },
        shopcart => My::Cool::Shopping::Cart->new(),
    };

The Template Toolkit will automatically Do The Right Thing to access the data in an appropriate manner to return some value which can then be output. The dot operator '.' is used to accesses into lists and hashes or to call object methods. The FOREACH directive is provided for iterating through lists, and various logicial tests are available using directives such as IF, UNLESS, ELSIF, ELSE, SWITCH, CASE, etc.

    [% FOREACH section = menu %]
       <a href="[% root %]/[% section %]/index.html">[% section %]</a>
    [% END %]
    <b>Client</a>: [% client.name %] (id: [% client.id %])

    [% IF shopcart.nitems %]
       Your shopping cart contains the following items:
       <ul>
       [% FOREACH item = shopcart.contents %]
          <li>[% item.name %] : [% item.qty %] @ [% item.price %]
       [% END %]
       </ul>
       [% checkout(shopcart.total) %]
    [% ELSE %]
       No items currently in shopping cart.
    [% END %]

The Template Toolkit also provides a number of additional directives for advanced processing and programmatical functionality. It supports output filters (FILTER), allows custom macros to be defined (MACRO), has a fully-featured exception handling system (TRY, THROW, CATCH, FINAL) and supports a plugin architecture (USE) which allows special plugin modules and even regular Perl modules to be loaded and used with the minimum of fuss. The Template Toolkit is ``just'' a template processor but you can trivially extend it to incorporate the functionality of any Perl module you can get your hands on. Thus, it is also a scalable and extensible template framework, ideally suited for managing the presentation layer for application servers, content management systems and other web applications.

Rather than embedding Perl code or some other scripting language directly into template documents, it encourages you to keep functional components (i.e. Perl code) separate from presentation components (e.g. HTML templates). The template variables provide the interface between the two layers, allowing data to be generated in code and then passed to a template component for displaying (pipeline model) or for sub-routine or object references to be bound to variables which can then be called from the template as and when required (callback model).

The directives that the Template Toolkit provide implement their own mini programming language, but they're not really designed for serious, general purpose programming. Perl is a far more appropriate language for that. If you embed application logic (e.g. Perl or other scripting language fragments) in HTML templates then you risk losing the clear separation of concerns between functionality and presentation. It becomes harder to maintain the two elements in isolation and more difficult, if not impossible, to reuse code or presentation elements by themselves. It is far better to write your application code in separate Perl modules, libraries or scripts and then use templates to control how the resulting data is presented as output. Thus you should think of the Template Toolkit language as a set of layout directives for displaying data, not calculating it.

Having said that, the Template Toolkit doesn't force you into one approach or the other. It attempts to be pragmatic rather than dogmatic in allowing you to do whatever best gets the job done. Thus, if you enable the EVAL_PERL option then you can happily embed real Perl code in your templates within PERL ... END directives.

The Template Toolkit uses a fast YACC-like parser which compiles templates into Perl code for maximum runtime efficiency. It also has an advanced caching mechanism which manages in-memory and on-disk (i.e. persistant) versions of compiled templates. The modules that comprise the toolkit are highly configurable and the architecture around which they're built is designed to be extensible. The Template Toolkit provides a powerful framework around which content creation and delivery systems can be built while also providing a simple interface through the Template front-end module for general use.


METHODS

new(\%config)

The new() constructor method (implemented by the Template::Base base class) instantiates a new Template object. A reference to a hash array of configuration items may be passed as a parameter.

    my $tt = Template->new({
        INCLUDE_PATH => '/usr/local/templates',
        EVAL_PERL    => 1,
    }) || die $Template::ERROR, "\n";

A reference to a new Template object is returned, or undef on error. In the latter case, the error message can be retrieved by calling error() as a class method (e.g. Template->error()) or by examining the $ERROR package variable directly (e.g. $Template::ERROR).

    my $tt = Template->new(\%config)
        || die Template->error(), "\n";
    my $tt = Template->new(\%config)
        || die $Template::ERROR, "\n";

For convenience, configuration items may also be specified as a list of items instead of a hash array reference. These are automatically folded into a hash array by the constructor.

    my $tt = Template->new(INCLUDE_PATH => '/tmp', POST_CHOMP => 1)
        || die $Template::ERROR, "\n";

process($template, \%vars, $output)

The process() method is called to process a template. The first parameter indicates the input template as one of: a filename relative to INCLUDE_PATH, if defined; a reference to a text string containing the template text; or a file handle reference (e.g. IO::Handle or sub-class) or GLOB (e.g. \*STDIN), from which the template can be read. A reference to a hash array may be passed as the second parameter, containing definitions of template variables.

    $text = "[% INCLUDE header %]\nHello world!\n[% INCLUDE footer %]";
    # filename
    $tt->process('welcome.tt2')
        || die $tt->error(), "\n";
    # text reference
    $tt->process(\$text)
        || die $tt->error(), "\n";
    # GLOB
    $tt->process(\*DATA)
        || die $tt->error(), "\n";
    __END__
    [% INCLUDE header %]
    This is a template defined in the __END__ section which is 
    accessible via the DATA "file handle".
    [% INCLUDE footer %]

By default, the processed template output is printed to STDOUT. The process() method then returns 1 to indicate success. A third parameter may be passed to the process() method to specify a different output location. This value may be one of: a plain string indicating a filename which will be opened (relative to OUTPUT_PATH, if defined) and the output written to; a file GLOB opened ready for output; a reference to a scalar (e.g. a text string) to which output/error is appended; a reference to a subroutine which is called, passing the output as a parameter; or any object reference which implements a 'print' method (e.g. IO::Handle, Apache::Request, etc.) which will be called, passing the generated output as a parameter.

Examples:

    # output filename
    $tt->process('welcome.tt2', $vars, 'welcome.html')
        || die $tt->error(), "\n";
    # reference to output subroutine
    sub myout {
        my $output = shift;
        ...
    }
    $tt->process('welcome.tt2', $vars, \&myout)
        || die $tt->error(), "\n";
    # reference to output text string
    my $output = '';
    $tt->process('welcome.tt2', $vars, \$output)
        || die $tt->error(), "\n";

    print "output: $output\n";

In an Apache/mod_perl handler:

    sub handler {
        my $req = shift;
        ...
        # direct output to Apache::Request via $req->print($output)
        $tt->process($file, $vars, $req) || do {
            $req->log_reason($tt->error());
            return SERVER_ERROR;
        };
        return OK;
    }

The OUTPUT configuration item can be used to specify a default output location other than \*STDOUT. The OUTPUT_PATH specifies a directory which should be prefixed to all output locations specified as filenames.

    my $tt = Template->new({
        OUTPUT      => sub { ... },       # default
        OUTPUT_PATH => '/tmp',
        ...
    }) || die Template->error(), "\n";
    # use default OUTPUT (sub is called)
    $tt->process('welcome.tt2', $vars)
        || die $tt->error(), "\n";
    # write file to '/tmp/welcome.html'
    $tt->process('welcome.tt2', $vars, 'welcome.html')
        || die $tt->error(), "\n";

The process() method returns 1 on success or undef on error. The error message generated in the latter case can be retrieved by calling the error() method. See also CONFIGURATION OPTIONS which describes how error handling may be further customised.

error()

When called as a class method, it returns the value of the $ERROR package variable. Thus, the following are equivalent.

    my $tt = Template->new()
        || die Template->error(), "\n";
    my $tt = Template->new()
        || die $Template::ERROR, "\n";

When called as an object method, it returns the value of the internal _ERROR variable, as set by an error condition in a previous call to process().

    $tt->process('welcome.tt2')
        || die $tt->error(), "\n";

Errors are represented in the Template Toolkit by objects of the Template::Exception class. If the process() method returns a false value then the error() method can be called to return an object of this class. The type() and info() methods can called on the object to retrieve the error type and information string, respectively. The as_string() method can be called to return a string of the form ``$type - $info''. This method is also overloaded onto the stringification operator allowing the object reference itself to be printed to return the formatted error string.

    $tt->process('somefile') || do {
        my $error = $tt->error();
        print "error type: ", $error->type(), "\n";
        print "error info: ", $error->info(), "\n";
        print $error, "\n";
    };

service()

The Template module delegates most of the effort of processing templates to an underlying Template::Service object. This method returns a reference to that object.

context()

The Template::Service module uses a core Template::Context object for runtime processing of templates. This method returns a reference to that object and is equivalent to $template->service->context();


TEMPLATE SYNTAX

By default, template directives are embedded within the character sequences '[%' and '%]'. e.g.

    [% PROCESS header %]

    <h1>Hello World!</h1>
    <a href="[% page.next %]"><img src="[% icon.next %].gif"></a>

    [% PROCESS footer %]

You can change the tag characters using the START_TAG, END_TAG and TAG_STYLE configuration options. You can also use the TAGS directive to define a new tag style for the current template file.

Directives may be embedded anywhere in a line of text and can be split across several lines. Insignificant whitespace is generally ignored within the directive.

    [% INCLUDE header              
       title = 'Hello World' 
       bgcol = '#ffffff' 
    %]

    [%INCLUDE menu align='right'%]

    Name: [% name %]  ([%id%])

You can also set the INTERPOLATE option to allow simple variable references to be embedded directly in templates, prefixed by a '$'.

    # INTERPOLATE => 0
    <td>[% name %]</td>  <td>[% email %]</td>
    # INTERPOLATE => 1
    <td>$name</td>  <td>$email</td>

The '#' character is used to indicate comments within a directive. When placed immediately inside the opening directive tag, it causes the entire directive to be ignored.

    [%# this entire directive is ignored no
        matter how many lines it wraps onto
    %]

In any other position, it causes the remainder of the current line to be treated as a comment.

    [% # this is a comment
       theta = 20      # so is this
       rho   = 30      # <aol>me too!</aol>
    %]

You can add '-' or '+' to the immediate start or end of a directive tag to control the whitespace chomping options. See the PRE_CHOMP and POST_CHOMP options for further details.

    [% BLOCK foo -%]            # remove trailing newline
    This is block foo
    [%- END %]                  # remove leading newline

The simplest directives are GET and SET which retrieve and update variable values respectively. The GET and SET keywords are actually optional as the parser is smart enough to see them for what they really are (but note the caveat below on using side-effect notation). Thus, you'll generally see:

    [% SET foo = 10 %]
    [% GET foo %]

written as:

    [% foo = 10 %]
    [% foo %]

You can also express simple logical statements as implicit GET directives:

    [% title or template.title or 'Default Title' %]
    [% mode == 'graphics' ? "Graphics Mode Enabled" : "Text Mode" %]

All other directives should start with a keyword specified in UPPER CASE (but see the ANYCASE option). All directives keywords are in UPPER CASE to make them visually distinctive and to distinguish them from variables of the same name but different case. It is perfectly valid, for example, to define a variable called 'stop' which is entirely separate from the STOP directive.

    [% stop = 'Clackett Lane Bus Depot' %]
    The bus will next stop at [% stop %]    # variable
    [% STOP %]                              # directive

Directives such as FOREACH, WHILE, BLOCK, FILTER, etc., mark the start of a block which may contain text or other directives up to the matching END directive. Blocks may be nested indefinately. The IF, UNLESS, ELSIF and ELSE directives also define blocks and may be grouped together in the usual manner.

    [% FOREACH item = [ 'foo' 'bar' 'baz' ] %]
       * Item: [% item %]
    [% END %]

    [% BLOCK footer %]
       Copyright 2000 [% me %]
       [% INCLUDE company/logo %]
    [% END %]

    [% IF foo %]
       [% FOREACH thing = foo.things %]
          [% thing %]
       [% END %]
    [% ELSIF bar %]
       [% INCLUDE barinfo %]
    [% ELSE %]
       do nothing...
    [% END %]

Block directives can also be used in a convenient side-effect notation.

    [% INCLUDE userinfo FOREACH user = userlist %]
    [% INCLUDE debugtxt msg="file: $error.info" 
         IF debugging %]
    [% "Danger Will Robinson" IF atrisk %]

versus:

    [% FOREACH user = userlist %]
       [% INCLUDE userinfo %]
    [% END %]
    [% IF debugging %]
       [% INCLUDE debugtxt msg="file: $error.info" %]
    [% END %]
    [% IF atrisk %]
    Danger Will Robinson
    [% END %]

The output of a directive can be captured by simply assigning the directive to a variable.

    [% headtext = PROCESS header title="Hello World" %]
    [% people = PROCESS userinfo FOREACH user = userlist %]

This can be used in conjunction with the BLOCK directive for defining large blocks of text or other content.

    [% poem = BLOCK %]
       The boy stood on the burning deck,
       His fleece was white as snow.
       A rolling stone gathers no moss,
       And Keith is sure to follow.
    [% END %]

Note one important caveat of using this syntax in conjunction with side-effect notation. The following directive does not behave as might be expected:

    [% var = 'value' IF some_condition %]

In this case, the directive is interpreted as (spacing added for clarity)

    [% var = IF some_condition %]
       value
    [% END %]

rather than

    [% IF some_condition %]
       [% var = 'value' %]
    [% END %]

The variable is assigned the output of the IF block which returns 'value' if true, but nothing if false. In other words, the following directive will always cause 'var' to be cleared.

    [% var = 'value' IF 0 %]

To achieve the expected behaviour, the directive should be written as:

    [% SET var = 'value' IF some_condition %]

Multiple FILTER directives can be chained together in sequence. They are called in the order defined, piping the output of one into the input of the next.

    [% PROCESS somefile FILTER truncate(100) FILTER html %]

The pipe character, '|', can also be used as an alias for FILTER.

    [% PROCESS somefile | truncate(100) | html %]

Multiple directives can be included within a single tag when delimited by semi-colons, ';'. Note however that the TAGS directive must always be specified in a tag by itself.

    [% IF title; 
          INCLUDE header; 
       ELSE; 
          INCLUDE other/header  title="Some Other Title";
       END
    %]

versus

    [% IF title %]
       [% INCLUDE header %]
    [% ELSE %]
       [% INCLUDE other/header  title="Some Other Title" %]
    [% END %]


TEMPLATE VARIABLES

A reference to a hash array may be passed as the second argument to the process() method, containing definitions of template variables. The VARIABLES (a.k.a. PRE_DEFINE) option can also be used to pre-define variables for all templates processed by the object.

    my $tt = Template->new({
        VARIABLES => {
            version => 3.14,
            release => 'Sahara',
        },
    });
    my $vars = {
        serial_no => 271828,
    };
    $tt->process('myfile', $vars);

'myfile':

    This is version [% version %] ([% release %]).
    Serial number: [% serial_no %]

output:

    This is version 3.14 (Sahara)
    Serial number: 271828

Variable names may contain any alphanumeric characters or underscores. They may be lower, upper or mixed case although the usual convention is to use lower case. The case is significant however, and 'foo', 'Foo' and 'FOO' are all different variables. Upper case variable names are permitted, but not recommended due to a possible conflict with an existing or future reserved word. As of version 2.00, these are:

    GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER 
    IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
    USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
    TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP 
    CLEAR TO STEP AND OR NOT MOD DIV END

The variable values may be of virtually any Perl type, including simple scalars, references to lists, hash arrays, subroutines or objects. The Template Toolkit will automatically apply the correct procedure to accessing these values as they are used in the template.

Example:

    my $vars = {
        article => 'The Third Shoe',
        person  => { 
            id    => 314, 
            name  => 'Mr. Blue',
            email => 'blue@nowhere.org',
        },
        primes  => [ 2, 3, 5, 7, 11, 13 ],
        wizard  => sub { return join(' ', 'Abracadabra!', @_) },
        cgi     => CGI->new('mode=submit&debug=1'),
    };

template:

    [% article %]
    [% person.id %]: [% person.name %] <[% person.email %]>
    [% primes.first %] - [% primes.last %], including [% primes.3 %]
    [% primes.size %] prime numbers: [% primes.join(', ') %]
    [% wizard %]
    [% wizard('Hocus Pocus!') %]
    [% cgi.param('mode') %]

output:

    The Third Shoe
    314: Mr. Blue <blue@nowhere.org>
    2 - 13, including 7
    6 prime numbers: 2, 3, 5, 7, 11, 13
    Abracadabra!
    Abracadabra! Hocus Pocus!

    submit

Scalar Values

Regular scalar variables are accessed by simply specifying their name. As these are just entries in the top-level variable hash they can be considered special cases of hash array referencing as described below, with the main namespace hash automatically implied.

    [% article %]

Hash Array References

Members of hash arrays are accessed by specifying the hash reference and key separated by the dot '.' operator.

    my $vars = {
        'home' => 'http://www.myserver.com/homepage.html',
        'page' => {
            'this' => 'mypage.html',
            'next' => 'nextpage.html',
            'prev' => 'prevpage.html',
        },
    };

template:
    <a href="[% home %]">Home</a>
    <a href="[% page.prev %]">Previous Page</a>
    <a href="[% page.next %]">Next Page</a>

output:

    <a href="http://www.myserver.com/homepage.html";>Home</a>
    <a href="prevpage.html">Previous Page</a>
    <a href="nextpage.html">Next Page</a>

Any key in a hash which starts with a '_' or '.' character will be considered private and cannot be evaluated or updated from within a template. The undefined value will be returned for any such variable accessed which the Template Toolkit will silently ignore (unless the DEBUG option is enabled).

    my $vars = {
        message => 'Hello World!',
        _secret => "On the Internet, no-one knows you're a dog",
        thing   => {
             public  => 123,
            _private => 456,
           '.hidden' => 789,
        },
    };

template:

    [% message %]               # outputs "Hello World!"
    [% _secret %]               # no output
    [% thing.public %]          # outputs "123"
    [% thing._private %]        # no output
    [% thing..hidden %]         # ERROR: unexpected token (..)

To access a hash entry using a key stored in another variable, prefix the key variable with '$' to have it interpolated before use (see Variable Interpolation).

    [% pagename = 'next' %]
    [% page.$pagename %]       # same as [% page.next %]

When you assign to a variable that contains multiple namespace elements (i.e. it has one or more '.' characters in the name), any hashes required to represent intermediate namespaces will be created automatically. In this following example, the 'product' variable automatically springs into life as a hash array unless otherwise defined.

    [% product.id    = 'XYZ-2000' 
       product.desc  = 'Bogon Generator'
       product.price = 666 
    %]

    The [% product.id %] [% product.desc %] 
    costs $[% product.price %].00

output:

    The XYZ-2000 Bogon Generator 
    costs $666.00

You can use Perl's familiar '{' ... '}' construct to explicitly create a hash and assign it to a variable. Note that commas are optional between key/value pairs and '=' can be used in place of '=>'.

    [% product = {
         id    => 'XYZ-2000',
         desc  => 'Bogon Generator',
         price => 666,
       }
    %]

List References

Items in lists are also accessed by use of the dot operator.

    my $vars = {
        'people' => [ 'Tom', 'Dick', 'Larry' ],
    };

template:

    [% people.0 %]                      # Tom
    [% people.1 %]                      # Dick
    [% people.2 %]                      # Larry

The FOREACH directive can be used to iterate through items in a list.

    [% FOREACH person = people %]
    Hello [% person %]
    [% END %]

output:

    Hello Tom
    Hello Dick
    Hello Larry

Lists can be constructed in-situ using the regular anonymous list '[' ... ']' construct. Commas between items are optional.

    [% cols = [ 'red', 'green', 'blue' ] %]
    [% FOREACH c = cols %]
       ...

or:

    [% FOREACH c = [ 'red', 'green', 'blue' ] %]
       ...

You can also create simple numerical sequences using the familiar '..' operator:

    [% n = [ 1 .. 4 ] %]    # n is [ 1, 2, 3, 4 ]
    [% x = 4
       y = 8
       z = [x..y]           # z is [ 4, 5, 6, 7, 8 ]
    %]

Subroutines

Template variables can contain references to Perl subroutines. When the variable is used, the Template Toolkit will automatically call the subroutine, passing any additional arguments specified. The return value from the subroutine is used as the variable value and inserted into the document output.

    my $vars = {
        wizard  => sub { return join(' ', 'Abracadabra!', @_) },
    };

template:

    [% wizard %]                        # Abracadabra!
    [% wizard('Hocus Pocus!') %]        # Abracadabra! Hocus Pocus!

Objects

Template variables can also contain references to Perl objects. Methods are called using the dot operator to specify the method against the object variable. Additional arguments can be specified as with subroutines.

    use CGI;
    ...
    my $vars = {
        # hard coded CGI params for purpose of example
        cgi  => CGI->new('mode=submit&debug=1'),
    };

template:

    [% FOREACH p = cgi.param %]         # returns list of param keys
    [% p %] => [% cgi.param(p) %]       # fetch each param value
    [% END %]

output:

    mode => submit
    debug => 1

Object methods can also be called as lvalues. That is, they can appear on the left side of an assignment. The method will be called passing the assigning value as an argument.

    [% myobj.method = 10 %]

equivalent to:

    [% myobj.method(10) %]

Parameters and Return Values

Subroutines and methods will be passed any arguments specified in the template. Any template variables in the argument list will first be evaluated and their resultant values passed to the code.

    my $vars = {
        mycode => sub { return 'received ' . join(', ', @_) },
    };

template:

    [% foo = 10 %]
    [% mycode(foo, 20) %]               # received 10, 20

Named parameters may also be specified. These are automatically collected into a single hash array which is passed by reference as the last parameter to the sub-routine. Named parameters can be specified using either '=>' or '=' and can appear anywhere in the argument list.

    my $vars = {
        myjoin => \&myjoin,
    };
    sub myjoin {
        # look for hash ref as last argument
        my $params = ref $_[-1] eq 'HASH' ? pop : { };
        return join($params->{ joint } || ' + ', @_);
    }

template:

    [% myjoin(10, 20, 30) %]
    [% myjoin(10, 20, 30, joint = ' - ' %]
    [% myjoin(joint => ' * ', 10, 20, 30 %]

output:

    10 + 20 + 30
    10 - 20 - 30
    10 * 20 * 30

Parenthesised parameters may be added to any element of a variable, not just those that are bound to code or object methods. At present, parameters will be ignored if the variable isn't ``callable'' but are supported for future extensions. Think of them as ``hints'' to that variable, rather than just arguments passed to a function.

    [% r = 'Romeo' %]
    [% r(100, 99, s, t, v) %]           # outputs "Romeo"

User code should return a value for the variable it represents. This can be any of the Perl data types described above: a scalar, or reference to a list, hash, subroutine or object. Where code returns a list of multiple values the items will automatically be folded into a list reference which can be accessed as per normal.

    my $vars = {
        # either is OK, first is recommended
        items1 => sub { return [ 'foo', 'bar', 'baz' ] },
        items2 => sub { return ( 'foo', 'bar', 'baz' ) },
    };

template:

    [% FOREACH i = items1 %]
       ...
    [% END %]
    [% FOREACH i = items2 %]
       ...
    [% END %]

Error Handling

Errors can be reported from user code by calling die(). Errors raised in this way are caught by the Template Toolkit and converted to structured exceptions which can be handled from within the template. A reference to the exception object is then available as the 'error' variable.

    my $vars = {
        barf => sub { 
            die "a sick error has occured\n";
        },
    };

template:

    [% TRY %]
       [% barf %]           # calls sub which throws error via die()
    [% CATCH %]
       [% error.info %]     # outputs "a sick error has occured\n"
    [% END %]

Error messages thrown via die() are converted to exceptions of type 'undef'. Exceptions of user-defined types can be thrown by calling die() with a reference to a Template::Exception object.

    use Template::Exception;
    ...

    my $vars = {
        login => sub { 
            ...
            die Template::Exception->new('badpwd',
                                         'password too silly');
        },
    };

template:

    [% TRY %]
       [% login %]
    [% CATCH badpwd %]
       Bad password: [% error.info %]
    [% CATCH %]
       Some other '[% error.type %]' error: [% error.info %]
    [% END %]

The exception types 'stop' and 'return' are used to implement the STOP and RETURN directives. Throwing an exception as:

    die Template::Exception->new('stop');

has the same effect as the directive:

    [% STOP %]

Subroutines and methods can also raise errors by returning a list or reference to a list containing the undefined value (undef) followed by an exception object or error message. This is supported for backwards compatability with version 1 but may be deprecated in some future version.

    my $vars = {
        # currently equivalent
        barf => sub {
            die "I'm sorry Dave, I can't do that";
        },
        yack => sub {
            return (undef, "I'm sorry Dave, I can't do that");
        },
    };

Virtual Variable Methods

The Template Toolkit provides virtual methods for manipulating variable values. Most of them are analagous to regular Perl functions of the same names.

The following methods can be called against any scalar value:

defined
Returns true if the value is defined.
    [% user = get_user(uid) IF uid.defined %]

length
Returns the length of the string representation of the item:
    [% IF password.length < 8 %]
       Password too short, dumbass!
    [% END %]

split
Calls Perl's split() function to split a string into a list of strings.
    [% FOREACH dir = mypath.split(':') %]
       [% dir %]
    [% END %]

The following can be called against hash references.

keys, values, each
The regular hash operators returning lists of keys, values or both. Note how we use a '$' prefix on the 'key' variable in this example to have it interpolated (i.e. replaced with its value) before use.
    [% FOREACH key = product.keys %]
       [% key %] => [% product.$key %]
    [% END %]

sort, nsort
Return a list of the keys, sorted alphabetically (sort) or numerically (nsort) according to the corresponding values in the hash.
    [% FOREACH n = phones.sort %]
       [% phones.$n %] is [% n %],
    [% END %]

import
The import method can be called on a hash array to import the contents of another hash array.
    [% hash1 = {
           foo => 'Foo',
           bar => 'Bar',
       }
       hash2 = {
           wiz => 'Wiz',
           woz => 'Woz',
       }
    %]
    [% hash1.import(hash2) %]
    [% hash1.wiz %]                     # Wiz

You can also call the import() method by itself to import a hash array into the current namespace hash.

    [% user = { id => 'lwall', name => 'Larry Wall' } %]
    [% import(user) %]
    [% id %]: [% name %]                # lwall: Larry Wall

The following virtual methods are provided for lists:

first, last
Returns the first/last item in the list. The item is not removed from the list.
    [% results.first %] to [% results.last %]

size, max
Returns the size of a list (number of elements) and the maximum index number (size - 1), respectively.
    [% results.size %] search results matched your query

reverse
Returns the items of the list in reverse order.
    [% FOREACH s = scores.reverse %]
       ...
    [% END %]

join
Joins the items in the list into a single string, using Perl's join function.
    [% items.join(', ') %]

sort, nsort
Returns the items in alpha (sort) or numerical (nsort) order.
    [% library = books.sort %]

Where the list contains hash array references, a hash key can be passed as an argument to specify the sort field.

    [% library = books.sort('author') %]

unshift(), push()
Adds an item to the start/end of a list.
    [% mylist.unshift('prev item') %]
    [% mylist.push('next item')    %]

shift(), pop()
Removes the first/last item from the list and returns it.
    [% first = mylist.shift %]
    [% last  = mylist.pop   %]

The following example demonstrates how an empty list ('folk') can be populated with formatted strings by using the push() method in conjunction with a FOREACH loop. The resultant list can then be printed using join.

    [% # define some initial data
       people   => [ 
           { id => 'tom',   name => 'Tom'     },
           { id => 'dick',  name => 'Richard' },
           { id => 'larry', name => 'Larry'   },
       ]
       # define an empty list that list methods can be called against
       folk = [] 
    -%]
    [% folk.push("<a href=\"${person.id}.html\">$person.name</a>")
         FOREACH person = people.sort('name') -%]
    [% folk.join(",\n") %]

Output:

    <a href="larry.html">Larry</a>,
    <a href="dick.html">Richard</a>,
    <a href="tom.html">Tom</a>

You can define your own virtual methods for scalars, lists and hash arrays. The Template::Stash package variables $SCALAR_OPS, $LIST_OPS and $HASH_OPS are references to hash arrays that define these virtual methods. HASH_OPS and LIST_OPS methods are subroutines that accept a hash/list reference as the first item. SCALAR_OPS are subroutines that accept a scalar value as the first item. Any other arguments specified when the method is called will be passed to the subroutine.

    # load Template::Stash to make method tables visible
    use Template::Stash;
    # define list method to return new list of odd numbers only
    $Template::Stash::LIST_OPS->{ odd } = sub {
        my $list = shift;
        return [ grep { $_ % 2 } @$list ];
    };

template:

    [% primes = [ 2, 3, 5, 7, 9 %] %]
    [% primes.odd.join(', ') %]         # 3, 5, 7, 9

See also the examples in the t/vmeth.t test script.

Compound Variables

Compound 'dotted' variables may contain any number of separate elements. Each element may evaluate to any of the permitted variable types and the processor will then correctly use this value to evaluate the rest of the variable. Arguments may be passed to any of the intermediate elements.

    [% myorg.people.sort('surname').first.fullname %]

Intermediate variables may be used and will behave entirely as expected.

    [% sorted = myorg.people.sort('surname') %]
    [% sorted.first.fullname %]

This simplified dotted notation has the benefit of hiding the implementation details of your data. For example, you could implement a data structure as a hash array one day and then change it to an object the next without requiring any change to the templates.

Variable Interpolation

The Template Toolkit uses '$' consistently to indicate that a variable should be interpolated in position. Most frequently, you see this in double-quoted strings:

    [% fullname = "$honorific $firstname $surname" %]

Or embedded in plain text when the INTERPOLATE option is set:

    Dear $honorific $firstname $surname,

The same rules apply within directives. If a variable is prefixed with a '$' then it is replaced with its value before being used. The most common use is to retrieve an element from a hash where the key is stored in a variable.

    [% uid = 'abw' %]
    [% userlist.$uid %]             # same as 'userlist.abw'

Curly braces can be used to delimit interpolated variable names where necessary.

    [% userlist.${me.id}.name %]

Directives such as INCLUDE, PROCESS, etc., that accept a template name as the first argument, will automatically quote it for convenience.

    [% INCLUDE foo/bar.txt %]

equivalent to:

    [% INCLUDE "foo/bar.txt" %]

To INCLUDE a template whose name is stored in a variable, simply prefix the variable name with '$' to have it interpolated.

    [% myfile = 'header' %]
    [% INCLUDE $myfile %]

equivalent to:

    [% INCLUDE header %]

Note also that a variable containing a reference to a Template::Document object can also be processed in this way.

    my $vars = {
        header => Template::Document->new({ ... }),
    };

template:

    [% INCLUDE $header %]

Local and Global Variables

Any simple variables that you create, or any changes you make to existing variables, will only persist while the template is being processed. The top-level variable hash is copied before processing begins and any changes to variables are made in this copy, leaving the original intact. The same thing happens when you INCLUDE another template. The current namespace hash is cloned to prevent any variable changes made in the included template from interfering with existing variables. The PROCESS option bypasses the localisation step altogether making it slightly faster, but requiring greater attention to the possibility of side effects caused by creating or changing any variables within the processed template.

    [% BLOCK change_name %]
       [% name = 'bar' %]
    [% END %]
    [% name = 'foo' %] 
    [% INCLUDE change_name %]
    [% name %]                      # foo
    [% PROCESS change_name %]
    [% name %]                      # bar

Dotted compound variables behave slightly differently because the localisation process is only skin deep. The current variable namespace hash is copied, but no attempt is made to perform a deep-copy of other structures within it (hashes, arrays, objects, etc). A variable referencing a hash, for example, will be copied to create a new reference but which points to the same hash. Thus, the general rule is that simple variables (undotted variables) are localised, but existing complex structures (dotted variables) are not.

    [% BLOCK all_change %]
       [% x = 20 %]                 # changes copy
       [% y.z = 'zulu' %]           # changes original
    [% END %]
    [% x = 10
       y = { z => 'zebra' }
    %]
    [% INCLUDE all_change %]
    [% x %]                         # still '10'
    [% y.z %]                       # now 'zulu'

If you create a complex structure such as a hash or list reference within a local template context then it will cease to exist when the template is finished processing.

    [% BLOCK new_stuff %]
       [% # define a new 'y' hash array in local context
          y = { z => 'zulu' }
       %]
    [% END %]
    [% x = 10 %]
    [% INCLUDE new_stuff %]
    [% x %]                         # outputs '10'
    [% y %]                         # nothing, y is undefined

Similarly, if you update an element of a compound variable which doesn't already exists then a hash will be created automatically and deleted again at the end of the block.

    [% BLOCK new_stuff %]
       [% y.z = 'zulu' %]
    [% END %]

However, if the hash does already exist then you will modify the original with permanent effect. To avoid potential confusion, it is recommended that you don't update elements of complex variables from within blocks or templates included by another.

If you want to create or update truly global variables then you can use the 'global' namespace. This is a hash array automatically created in the top-level namespace which all templates, localised or otherwise see the same reference to. Changes made to variables within this hash are visible across all templates.

    [% global.version = 123 %]

Special Variables

A number of special variables are automatically defined by the Template Toolkit.

template
The 'template' variable contains a reference to the main template being processed, in the form of a Template::Document object. This variable is correctly defined within PRE_PROCESS, PROCESS and POST_PROCESS templates, allowing standard headers, footers, etc., to access metadata items from the main template. The 'name' and 'modtime' metadata items are automatically provided, giving the template name and modification time in seconds since the epoch.

Note that the 'template' variable always references the top-level template, even when processing other template components via INCLUDE, PROCESS, etc.

component
The 'component' variable is like 'template' but always contains a reference to the current, innermost template component being processed. In the main template, the 'template' and 'component' variable will reference the same Template::Document object. In any other template component called from the main template, the 'template' variable will remain unchanged, but 'component' will contain a new reference to the current component.

This example should demonstrate the difference:

    $template->process('foo')
        || die $template->error(), "\n";

'foo':

    [% template.name %]             # foo
    [% component.name %]            # foo
    [% PROCESS footer %]

'footer':

    [% template.name %]             # foo
    [% component.name %]            # footer

loop
Within a FOREACH loop, the 'loop' variable references the Template::Iterator object responsible for controlling the loop.
    [% FOREACH item = [ 'foo', 'bar', 'baz' ] -%]
       [% "Items:\n" IF loop.first -%]
       [% loop.count %]/[% loop.size %]: [% item %]
    [% END %]

error
Within a CATCH block, the 'error' variable contains a reference to the Template::Exception object thrown from within the TRY block. The 'type' and 'info' methods can be called or the variable itself can be printed for automatic stringification into a message of the form ``$type error - $info''. See the Template::Exception manpage for further details.
    [% TRY %]
       ...
    [% CATCH %]
       [% error %]
    [% END %]

content
The WRAPPER method captures the output from a template block and then includes a named template, passing the captured output as the 'content' variable.
    [% WRAPPER box %]
    Be not afeard; the isle is full of noises,
    Sounds and sweet airs, that give delight and hurt not.
    [% END %]
    [% BLOCK box %]
    <table border=1>
    <tr>
      <td>
      [% content %]
      </td>
    </tr>
    </table>
    [% END %]


TEMPLATE DIRECTIVES

Accessing and Updating Template Variables

GET
The GET directive retrieves and outputs the value of the named variable.
    [% GET foo %]

The GET keyword is optional. A variable can be specified in a directive tag by itself.

    [% foo %]

The variable may take any of the forms described above:

    [% foo %]
    [% bar.baz %]
    [% biz.baz(10) %]
    ...etc...

You can also specify expressions using the logical (and, or, not, ?:) and mathematic operators (+ - * / % mod div).

    [% template.title or default.title %]
    [% score * 100 %]
    [% order.nitems ? checkout(order.total) : 'no items' %]

The 'div' operator returns the integer result of division. Both '%' and 'mod' return the modulus (i.e. remainder) of division. 'mod' is provided as an alias for '%' for backwards compatability with version 1.

    [% 15 / 6 %]            # 2.5
    [% 15 div 6 %]          # 2
    [% 15 mod 6 %]          # 3

CALL
The CALL directive is similar to GET in evaluating the variable named, but doesn't print the result returned. This can be useful when a variable is bound to a sub-routine or object method which you want to call but aren't interested in the value returned.
    [% CALL dbi.disconnect %]
    [% CALL inc_page_counter(page_count) %]

SET
The SET directive allows you to assign new values to existing variables or create new temporary variables.
    [% SET title = 'Hello World' %]

The SET keyword is also optional.


    [% title = 'Hello World' %]

Variables may be assigned the values of other variables, unquoted numbers (digits), literal text ('single quotes') or quoted text (``double quotes''). In the latter case, any variable references within the text will be interpolated when the string is evaluated. Variables should be prefixed by '$', using curly braces to explicitly scope the variable name where necessary.

    [% foo  = 'Foo'  %]               # literal value 'Foo'
    [% bar  =  foo   %]               # value of variable 'foo'
    [% cost = '$100' %]               # literal value '$100'
    [% item = "$bar: ${cost}.00" %]   # value "Foo: $100.00"

Multiple variables may be assigned in the same directive and are evaluated in the order specified. Thus, the above could have been written:

    [% foo  = 'Foo'
       bar  = foo
       cost = '$100'
       item = "$bar: ${cost}.00"
    %]

Simple expressions can also be used, as per GET.

    [% ten    = 10 
       twenty = 20
       thirty = twenty + ten
       forty  = 2 * twenty 
       fifty  = 100 div 2
       six    = twenty mod 7
    %]

DEFAULT
The DEFAULT directive is similar to SET but only updates variables that are currently undefined or have no ``true'' value (in the Perl sense).
    [% DEFAULT
       name = 'John Doe'
       id   = 'jdoe'
    %]

This can be particularly useful in common template components to ensure that some sensible default are provided for otherwise undefined variables.

    [% DEFAULT 
       title = 'Hello World'
       bgcol = '#ffffff'
    %]
    <html>
    <head>
    <title>[% title %]</title>
    </head>
    <body bgcolor="[% bgcol %]">

Processing Other Template Files and Blocks

INSERT
The INSERT directive is used to insert the contents of an external file at the current position.
    [% INSERT myfile %]

No attempt to parse or process the file is made. The contents, possibly including any embedded template directives, are inserted intact.

The filename specified should be relative to one of the INCLUDE_PATH directories. Absolute (i.e. starting with /) and relative (i.e. starting with .) filenames may be used if the ABSOLUTE and RELATIVE options are set, respectively. Both these options are disabled by default.

    my $template = Template->new({
        INCLUDE_PATH => '/here:/there',
    });
    $template->process('myfile');

'myfile':

    [% INSERT foo %]            # looks for /here/foo then /there/foo
    [% INSERT /etc/passwd %]    # file error: ABSOLUTE not set
    [% INSERT ../secret %]      # file error: RELATIVE not set

For convenience, the filename does not need to be quoted as long as it contains only alphanumeric characters, underscores, dots or forward slashes. Names containing any other characters should be quoted.

    [% INSERT misc/legalese.txt            %]
    [% INSERT 'dos98/Program Files/stupid' %]

To evaluate a variable to specify a filename, you should explicitly prefix it with a '$' or use double-quoted string interpolation.

    [% language = 'en'
       legalese = 'misc/legalese.txt' 
    %]
    [% INSERT $legalese %]              # 'misc/legalese.txt'
    [% INSERT "$language/$legalese" %]  # 'en/misc/legalese.txt'

INCLUDE
The INCLUDE directive is used to process and include the output of another template file or block.
    [% INCLUDE header %]

If a BLOCK of the specified name is defined in the same file, or in a file from which the current template has been called (i.e. a parent template) then it will be used in preference to any file of the same name.

    [% INCLUDE table %]             # uses BLOCK defined below
    [% BLOCK table %]
       <table>
       ...
       </table>
    [% END %]

If a BLOCK definition is not currently visible then the template name should be a file relative to one of the INCLUDE_PATH directories, or an absolute or relative file name if the ABSOLUTE/RELATIVE options are appropriately enabled. The INCLUDE directive automatically quotes the filename specified, as per INSERT described above. When a variable contains the name of the template for the INCLUDE directive, it should be explicitly prefixed by '$'.

    [% myheader = 'my/misc/header' %]
    [% INCLUDE  myheader %]              # 'myheader'
    [% INCLUDE $myheader %]              # 'my/misc/header'

Any template directives embedded within the file will be processed accordingly. All variables currently defined will be visible and accessible from within the included template.

    [% title = 'Hello World' %]
    [% INCLUDE header %]
    <body>
    ...

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

output: <html> <title>Hello World</title> <body> ...

Local variable definitions may be specified after the template name, temporarily masking any existing variables. Insignificant whitespace is ignore within directives so you can add variable definitions on the same line, the next line or split across several line with comments interspersed, if you prefer.

    [% INCLUDE table %]
    [% INCLUDE table title="Active Projects" %]
    [% INCLUDE table 
         title   = "Active Projects" 
         bgcolor = "#80ff00"    # chartreuse
         border  = 2
    %]

The INCLUDE directive localises (i.e. copies) all variables before processing the template. Any changes made within the included template will not affect variables in the including template.

    [% foo = 10 %]
    foo is originally [% foo %]
    [% INCLUDE bar %]
    foo is still [% foo %]
    [% BLOCK bar %]
       foo was [% foo %]
       [% foo = 20 %]
       foo is now [% foo %]
    [% END %]

output: foo is originally 10 foo was 10 foo is now 20 foo is still 10

Technical Note: the localisation of the stash (that is, the process by which variables are copied before an INCLUDE to prevent being overwritten) is only skin deep. The top-level variable namespace (hash) is copied, but no attempt is made to perform a deep-copy of other structures (hashes, arrays, objects, etc.) Therefore, a 'foo' variable referencing a hash will be copied to create a new 'foo' variable but which points to the same hash array. Thus, if you update compound variables (e.g. foo.bar) then you will change the original copy, regardless of any stash localisation. If you're not worried about preserving variable values, or you trust the templates you're including then you might prefer to use the PROCESS directive which is faster by virtue of not performing any localisation.

PROCESS
The PROCESS directive is similar to INCLUDE but does not perform any localisation of variables before processing the template. Any changes made to variables within the included template will be visible in the including template.
    [% foo = 10 %]
    foo is [% foo %]
    [% PROCESS bar %]
    foo is [% foo %]
    [% BLOCK bar %]
       [% foo = 20 %]
       changed foo to [% foo %]
    [% END %]

output:

    foo is 10
       changed foo to 20
    foo is 20

Parameters may be specified in the PROCESS directive, but these too will become visible changes to current variable values.

    [% foo = 10 %]
    foo is [% foo %]
    [% PROCESS bar
       foo = 20 
    %]
    foo is [% foo %]
    [% BLOCK bar %]
       this is bar, foo is [% foo %]
    [% END %]

output:

    foo is 10
       this is bar, foo is 20
    foo is 20

The PROCESS directive is slightly faster than INCLUDE because it avoids the need to localise (i.e. copy) the variable stash before processing the template. As with INSERT and INCLUDE, the first parameter does not need to be quoted as long as it contains only alphanumeric characters, underscores, periods or forward slashes. A '$' prefix can be used to explicitly indicate a variable which should be interpolated to provide the template name:

    [% myheader = 'my/misc/header' %]
    [% PROCESS  myheader %]              # 'myheader'
    [% PROCESS $myheader %]              # 'my/misc/header'

WRAPPER
It's not unusual to find yourself adding common headers and footers to pages or sub-sections within a page. Something like this:
    [% INCLUDE section/header
       title = 'Quantum Mechanics'
    %]
       Quantum mechanics is a very interesting subject wish 
       should prove easy for the layman to fully comprehend.
    [% INCLUDE section/footer %]
    [% INCLUDE section/header
       title = 'Desktop Nuclear Fusion for under $50'
    %]
       This describes a simple device which generates significant 
       sustainable electrical power from common tap water by process 
       of nuclear fusion.
    [% INCLUDE section/footer %]

The individual template components being included might look like these:

section/header: <p> <h2>[% title %]</h2>

section/footer: </p>

The WRAPPER directive provides a way of simplifying this a little. It encloses a block up to a matching END directive, which is first processed to generate some output. This is then passed to the named template file or BLOCK as the 'content' variable.

    [% WRAPPER section
       title = 'Quantum Mechanics'
    %]
       Quantum mechanics is a very interesting subject wish 
       should prove easy for the layman to fully comprehend.
    [% END %]
    [% WRAPPER section
       title = 'Desktop Nuclear Fusion for under $50'
    %]
       This describes a simple device which generates significant 
       sustainable electrical power from common tap water by process 
       of nuclear fusion.
    [% END %]

The single 'section' template can then be defined as:

    <p>
    <h2>[% title %]</h2>
    [% content %]
    </p>

Like other block directives, it can be used in side-effect notation:

    [% INSERT legalese.txt WRAPPER big_bold_table %]

BLOCK
The BLOCK ... END construct can be used to define template component blocks which can be processed with the INCLUDE, PROCESS and WRAPPER directives.
    [% BLOCK tabrow %]
    <tr><td>[% name %]<td><td>[% email %]</td></tr>
    [% END %]

    <table>
    [% PROCESS tabrow  name='Fred'  email='fred@nowhere.com' %]
    [% PROCESS tabrow  name='Alan'  email='alan@nowhere.com' %]
    </table>

A BLOCK definition can be used before it is defined, as long as the definition resides in the same file. The block definition itself does not generate any output.

    [% PROCESS tmpblk %]
    [% BLOCK tmpblk %] This is OK [% END %]

You can use an anonymous BLOCK to capture the output of a template fragment.

    [% julius = BLOCK %]
       And Caesar's spirit, ranging for revenge,
       With Ate by his side come hot from hell,
       Shall in these confines with a monarch's voice
       Cry  'Havoc', and let slip the dogs of war;
       That this foul deed shall smell above the earth
       With carrion men, groaning for burial.
    [% END %]

Like a named block, it can contain any other template directives which are processed when the block is defined. The output generated by the block is then assigned to the variable 'julius'.

Anonymous BLOCKs can also be used to define block macros. The enclosing block is processed each time the macro is called.

    [% MACRO whereabouts BLOCK %]
       The [% animal %] sat on the [% place %].
    [% END %]
    [% foo(animal='cat', place='mat') %]    # The cat sat on the mat
    [% foo(animal='dog', place='log') %]    # The dog sat on the log

Conditional Processing

IF / UNLESS / ELSIF / ELSE
The IF and UNLESS directives can be used to process or ignore a block based on some run-time condition.
    [% IF frames %]
       [% INCLUDE frameset %]
    [% END %]
    [% UNLESS text_mode %]
       [% INCLUDE biglogo %]
    [% END %]

Multiple conditions may be joined with ELSIF and/or ELSE blocks.

    [% IF age < 10 %]
       Hello [% name %], does your mother know you're 
       using her AOL account?
    [% ELSIF age < 18 %]
       Sorry, you're not old enough to enter 
       (and too dumb to lie about your age)
    [% ELSE %]
       Welcome [% name %].
    [% END %]

The following conditional and boolean operators may be used:

    == != < <= > >= ! && || and or not

Conditions may be arbitrarily complex and are evaluated with the same precedence as in Perl. Parenthesis may be used to explicitly determine evaluation order.

    # ridiculously contrived complex example
    [% IF (name == 'admin' || uid <= 0) && mode == 'debug' %]
       I'm confused.
    [% ELSIF more > less %]
       That's more or less correct.
    [% END %]

SWITCH / CASE
The SWITCH / CASE construct can be used to perform a multi-way conditional test. The SWITCH directive expects an expression which is first evaluated and then compared against each CASE statement in turn. Each CASE directive should contain a single value or a list of values which should match. CASE may also be left blank or written as [% CASE DEFAULT %] to specify a default match. Only one CASE matches, there is no drop-through between CASE statements.

    [% SWITCH myvar %]
    [% CASE value1 %]
       ...
    [% CASE [ value2 value3 ] %]   # multiple values
       ...
    [% CASE myhash.keys %]         # ditto
       ...
    [% CASE %]                     # default
       ...
    [% END %]

Loop Processing

FOREACH
The FOREACH directive will iterate through the items in a list, processing the enclosed block for each one.
    my $vars = {
        foo   => 'Foo',
        items => [ 'one', 'two', 'three' ],
    };

template:
    Things:
    [% FOREACH thing = [ foo 'Bar' "$foo Baz" ] %]
       * [% thing %]
    [% END %]

    Items:
    [% FOREACH i = items %]
       * [% i %]
    [% END %]

    Stuff:
    [% stuff = [ foo "$foo Bar" ] %]
    [% FOREACH s = stuff %]
       * [% s %]
    [% END %]

output:

    Things:
      * Foo
      * Bar
      * Foo Baz

    Items:
      * one
      * two
      * three

    Stuff:
      * Foo
      * Foo Bar

When the FOREACH directive is used without specifying a target variable, any iterated values which are hash references will be automatically imported.

    [% userlist = [
          { id => 'tom',   name => 'Thomas'  },
          { id => 'dick',  name => 'Richard'  },
          { id => 'larry', name => 'Lawrence' },
       ]
    %]
    [% FOREACH user = userlist %]
       [% user.id %] [% user.name %]
    [% END %]

short form:

    [% FOREACH userlist %]
       [% id %] [% name %]
    [% END %]

Note that this particular usage creates a localised variable context to prevent the imported hash keys from overwriting any existing variables. The imported definitions and any other variables defined in such a FOREACH loop will be lost at the end of the loop, when the previous context and variable values are restored.

The FOREACH directive can also be used to iterate through the entries in a hash array. Each entry in the hash is returned in sorted order (based on the key) as a hash array containing 'key' and 'value' items.

    [% users = {
         tom   => 'Thomas',
         dick  => 'Richard',
         larry => 'Lawrence',
       }
    %]
    [% FOREACH u = users %]
       * [% u.key %] : [% u.value %]
    [% END %]

Output:

       * dick : Richard
       * larry : Lawrence
       * tom : Thomas

The NEXT directive starts the next iteration in the FOREACH loop.

    [% FOREACH user = userlist %]
       [% NEXT IF user.isguest %]
       Name: [% user.name %]    Email: [% user.email %]
    [% END %]

The LAST directive can be used to prematurely exit the loop. BREAK is also provided as an alias for LAST.

    [% FOREACH match = results.nsort('score').reverse %]
       [% LAST IF match.score < 50 %]
       [% match.score %] : [% match.url %]
    [% END %]

The FOREACH directive is implemented using the Template::Iterator module. A reference to the iterator object for a FOREACH directive is implicitly available in the 'loop' variable. The following methods can be called on the 'loop' iterator.

    size()      number of elements in the list
    max()       index number of last element (size - 1)
    index()     index of current iteration from 0 to max()
    count()     iteration counter from 1 to size() (i.e. index() + 1)
    first()     true if the current iteration is the first
    last()      true if the current iteration is the last
    prev()      return the previous item in the list
    next()      return the next item in the list

See the Template::Iterator manpage for further details.

Example:

    [% FOREACH item = [ 'foo', 'bar', 'baz' ] -%]
       [%- "<ul>\n" IF loop.first %]
       <li>[% loop.count %]/[% loop.size %]: [% item %]
       [%- "</ul>\n" IF loop.last %]
    [% END %]

Output:

    <ul>
    <li>1/3: foo
    <li>2/3: bar
    <li>3/3: baz
    </ul>

Note that the number() method is supported as an alias for count() for backwards compatability but may be deprecated in some future version.

Nested loops will work as expected, with the 'loop' variable correctly referencing the innermost loop and being restored to any previous value (i.e. an outer loop) at the end of the loop.

    [% FOREACH group = grouplist %]
       [% "Groups:\n" IF loop.first %]        # loop => group iterator
       [% FOREACH user = group.userlist %]
          [% loop.count %]: [% user.name %]   # loop => user iterator
       [% END %]
       [% "End of Groups\n" IF loop.last %]   # loop => group iterator
    [% END %]

The 'iterator' plugin can also be used to explicitly create an iterator object. This can be useful within nested loops where you need to keep a reference to the outer iterator within the inner loop. The iterator plugin effectively allows you to create an iterator by a name other than 'loop'. See Template::Plugin::Iterator for further details.

    [% USE giter = iterator(grouplist) %]
    [% FOREACH group = giter %]
       [% FOREACH user = group.userlist %]
       user [% loop.count %] in group [% giter.count %]: [% user.name %]
       [% END %]
    [% END %]

WHILE
The WHILE directive can be used to repeatedly process a template block while a conditional expression evaluates true. The expression may be arbitrarily complex as per IF / UNLESS.
    [% WHILE total < 100 %]
       ...
       [% total = calculate_new_total %]
    [% END %]

An assignment can be enclosed in parenthesis to evaluate the assigned value.

    [% WHILE (user = get_next_user_record) %]
       [% user.name %]
    [% END %]

The NEXT directive can be used to start the next iteration of a WHILE loop and BREAK can be used to exit the loop, both as per FOREACH.

The Template Toolkit uses a failsafe counter to prevent runaway WHILE loops which would otherwise never terminate. If the loop exceeds 1000 iterations then an 'undef' exception will be thrown, reporting the error:

    WHILE loop terminated (> 1000 iterations)

The $Template::Directive::WHILE_MAX variable controls this behaviour and can be set to a higher value if necessary.

Filters, Plugins, Macros and Perl

FILTER
The FILTER directive can be used to post-process the output of a block. A number of standard filters are provided with the Template Toolkit. The 'html' filter, for example, escapes the '<', '>' and '&' characters to prevent them from being interpreted as HTML tags or entity reference markers.
    [% FILTER html %]
       HTML text may have < and > characters embedded
       which you want converted to the correct HTML entities.
    [% END %]

output:

       HTML text may have &lt; and &gt; characters embedded
       which you want converted to the correct HTML entities.

The FILTER directive can also follow various other non-block directives. For example:

    [% INCLUDE mytext FILTER html %]

The '|' character can also be used as an alias for 'FILTER'.

    [% INCLUDE mytext | html %]

Multiple filters can be chained together and will be called in sequence.

    [% INCLUDE mytext FILTER html FILTER html_para %]

or

    [% INCLUDE mytext | html | html_para %]

Filters come in two flavours, known as 'static' or 'dynamic'. A static filter is a simple subroutine which accepts a text string as the only argument and returns the modified text. The 'html' filter is an example of a static filter, implemented as:

    sub html_filter {
        my $text = shift;
        for ($text) {
            s/&/&amp;/g;
            s/</&lt;/g;
            s/>/&gt;/g;
        }
        return $text;
    }

Dynamic filters can accept arguments which are specified when the filter is called from a template. The 'repeat' filter is such an example, accepting a numerical argument which specifies the number of times that the input text should be repeated.

    [% FILTER repeat(3) %]blah [% END %]

output:

    blah blah blah

These are implemented as filter 'factories'. The factory subroutine is passed a reference to the current Template::Context object along with any additional arguments specified. It should then return a subroutine reference (e.g. a closure) which implements the filter. The 'repeat' filter factory is implemented like this:

    sub repeat_filter_factory {
        my ($context, $iter) = @_;
        $iter = 1 unless defined $iter;
        return sub {
            my $text = shift;
            $text = '' unless defined $text;
            return join('\n', $text) x $iter;
        }
    }

The FILTERS option, described in CONFIGURATION OPTIONS, allows custom filters to be defined when a Template object is instantiated. The Template::Context define_filter() method allows further filters to be defined at any time.

When using a filter, it is possible to assign an alias to it for further use. This is most useful for dynamic filters that you want to re-use with the same configuration.

    [% FILTER echo = repeat(2) %]
    Is there anybody out there?
    [% END %]
    [% FILTER echo %]
    Mother, should I build a wall?
    [% END %]

Output:

    Is there anybody out there?
    Is there anybody out there?
    Mother, should I build a wall?
    Mother, should I build a wall?

The FILTER directive automatically quotes the name of the filter. As with INCLUDE et al, you can use a variable to provide the name of the filter, prefixed by '$'.

    [% myfilter = 'html' %]
    [% FILTER $myfilter %]      # same as [% FILTER html %]
       ...
    [% END %]

A template variable can also be used to define a static filter subroutine. However, the Template Toolkit will automatically call any subroutine bound to a variable and use the value returned. Thus, the above example could be implemented as:

    my $vars = {
        myfilter => sub { return 'html' },
    };

template:

    [% FILTER $myfilter %]      # same as [% FILTER html %]
       ...
    [% END %]

To define a template variable that evaluates to a subroutine reference that can be used by the FILTER directive, you should create a subroutine that, when called automatically by the Template Toolkit, returns another subroutine reference which can then be used to perform the filter operation. Note that only static filters can be implemented in this way.

    my $vars = {
        myfilter => sub { \&my_filter_sub },
    };
    sub my_filter_sub {
        my $text = shift;
        # do something
        return $text;
    }

template:

    [% FILTER $myfilter %]
       ...
    [% END %]

Alternately, you can bless a subroutine reference into a class (any class will do) to fool the Template Toolkit into thinking it's an object rather than a subroutine. This will then bypass the automatic ``call-a-subroutine-to-return-a-value'' magic.

    my $vars = {
        myfilter => bless(\&my_filter_sub, 'anything_you_like'),
    };

template:

    [% FILTER $myfilter %]          
       ...
    [% END %]

Filters bound to template variables remain local to the variable context in which they are defined. That is, if you define a filter in a PERL block within a template that is loaded via INCLUDE, then the filter definition will only exist until the end of that template when the stash is delocalised, restoring the previous variable state. If you want to define a filter which persists for the lifetime of the processor, or define additional dynamic filter factories, then you can call the define_filter() method on the current Template::Context object.

See TEMPLATE TOOLKIT FILTERS for a complete list of available filters, their descriptions and examples of use.

USE
The USE directive can be used to load and initialise ``plugin'' extension modules.
    [% USE myplugin %]

A plugin is a regular Perl module that conforms to a particular object-oriented interface, allowing it to be loaded into and used automatically by the Template Toolkit. For details of this interface and information on writing plugins, consult the Template::Plugin manpage.

The plugin name is case-sensitive and will be appended to the PLUGIN_BASE value (default: 'Template::Plugin') to construct a full module name. Any periods, '.', in the name will be converted to '::'.

    [% USE MyPlugin %]     #  => Template::Plugin::MyPlugin
    [% USE Foo.Bar  %]     #  => Template::Plugin::Foo::Bar

Various standard plugins are included with the Template Toolkit (see below and TEMPLATE TOOLKIT PLUGINS). These can be specified in lower case and are mapped to the appropriate name.

    [% USE cgi   %]        # => Template::Plugin::CGI
    [% USE table %]        # => Template::Plugin::Table

Any additional parameters supplied in parenthesis after the plugin name will be also be passed to the new() constructor. A reference to the current Template::Context object is always passed as the first parameter.

    [% USE MyPlugin('foo', 123) %]

equivalent to:

    Template::Plugin::MyPlugin->new($context, 'foo', 123);

Named parameters may also be specified. These are collated into a hash which is passed by reference as the last parameter to the constructor, as per the general code calling interface.

    [% USE url('/cgi-bin/foo', mode='submit', debug=1) %]

equivalent to:

    Template::Plugin::URL->new($context, '/cgi-bin/foo'
                               { mode => 'submit', debug => 1 });

The plugin may represent any data type; a simple variable, hash, list or code reference, but in the general case it will be an object reference. Methods can be called on the object (or the relevant members of the specific data type) in the usual way:

    [% USE table(mydata, rows=3) %]
    [% FOREACH row = table.rows %]
       <tr>    
       [% FOREACH item = row %]
          <td>[% item %]</td>
       [% END %]
       </tr>
    [% END %]

An alternative name may be provided for the plugin by which it can be referenced:

    [% USE scores = table(myscores, cols=5) %]
    [% FOREACH row = scores.rows %]
       ...
    [% END %]

You can use this approach to create multiple plugin objects with different configurations. This example shows how the 'format' plugin is used to create sub-routines bound to variables for formatting text as per printf().

    [% USE bold = format('<b>%s</b>') %]
    [% USE ital = format('<i>%s</i>') %]
    [% bold('This is bold')   %]
    [% ital('This is italic') %]

Output:

    <b>This is bold</b>
    <i>This is italic</i>

This next example shows how the URL plugin can be used to build dynamic URLs from a base part and optional query parameters.

    [% USE mycgi = URL('/cgi-bin/foo.pl', debug=1) %]
    <a href="[% mycgi %]">...
    <a href="[% mycgi(mode='submit') %]"...

Output:

    <a href="/cgi-bin/foo.pl?debug=1">...
    <a href="/cgi-bin/foo.pl?mode=submit&debug=1">...

The CGI plugin is an example of one which delegates to another Perl module. In this this case, it is to Lincoln Stein's CGI.pm module. All of the methods provided by CGI.pm are available via the plugin.

    [% USE CGI %]
    [% CGI.start_form %]
    [% CGI.checkbox_group(name   =>   'colours', 
                          values => [ 'red' 'green' 'blue' ])
    %]
    [% CGI.popup_menu(name   =>   'items', 
                      values => [ 'foo' 'bar' 'baz' ])
    %]
    [% CGI.end_form %]

Simon Matthews has written the DBI plugin which provides an interface to Tim Bunce's DBI module (available from CPAN). Here's a short example:

    [% USE DBI('DBI:mSQL:mydbname') %]
    [% FOREACH user = DBI.query('SELECT * FROM users') %]
       [% user.id %] [% user.name %] [% user.etc.etc %]
    [% END %]

See TEMPLATE TOOLKIT PLUGINS for more information on the plugins distributed with the toolkit or available from CPAN.

The LOAD_PERL option (disabled by default) provides a further way by which external Perl modules may be loaded. If a regular Perl module (i.e. not a Template::Plugin::* or other module relative to some PLUGIN_BASE) supports an object-oriented interface and a new() constructor then it can be loaded and instantiated automatically. The following trivial example shows how the IO::File module might be used.

    [% USE file = IO.File('/tmp/mydata') %]
    [% WHILE (line = file.getline) %]
       <!-- [% line %] -->
    [% END %]

MACRO
The MACRO directive allows you to define a directive or directive block which is then evaluated each time the macro is called.
    [% MACRO header INCLUDE header %]

Calling the macro as:

    [% header %]

is then equivalent to:

    [% INCLUDE header %]

Macros can be passed named parameters when called. These values remain local to the macro.

    [% header(title='Hello World') %]

equivlant to:

    [% INCLUDE header title='Hello World' %]

A MACRO definition may include parameter names. Values passed to the macros are then mapped to these local variables. Other named parameters may follow these.

    [% MACRO header(title) INCLUDE header %]
    [% header('Hello World') %]
    [% header('Hello World', bgcol='#123456') %]

equivalent to:

    [% INCLUDE header title='Hello World' %]
    [% INCLUDE header title='Hello World' bgcol='#123456# %]

A MACRO may preceed any directive and must conform to the structure of the directive.

    [% MACRO header IF frames %]
       [% INCLUDE frames/header %]
    [% ELSE %]
       [% INCLUDE header %]
    [% END %]
    [% header %]

A MACRO may also be defined as an anonymous BLOCK. The block will be evaluated each time the macro is called.

    [% MACRO header BLOCK %]
       ...content...
    [% END %]
    [% header %]

PERL
The PERL directive is used to mark the start of a block which contains Perl code for evaluation. The EVAL_PERL option must be enabled for Perl code to be evaluated or a 'perl' exception will be thrown with the message 'EVAL_PERL not set'.

Perl code is evaluated in the Template::Perl package. The $context package variable contains a reference to the current Template::Context object. This can be used to access the functionality of the Template Toolkit to process other templates, load plugins, filters, etc. See the Template::Context manpage for further details.

    [% PERL %]
       print $context->include('myfile');
    [% END %]

The $stash variable contains a reference to the top-level stash object which manages template variables. Through this, variable values can be retrieved and updated. See the Template::Stash manpage for further details.

    [% PERL %]
       $stash->set(foo => 'bar');
       print "foo value: ", $stash->get('foo');
    [% END %]

Output foo value: bar

Output is generated from the PERL block by calling print(). Note that the Template::Perl::PERLOUT handle is selected (tied to an output buffer) instead of STDOUT.

    [% PERL %]
       print "foo\n";                           # OK
       print PERLOUT "bar\n";                   # OK, same as above
       print Template::Perl::PERLOUT "baz\n";   # OK, same as above
       print STDOUT "qux\n";                    # WRONG!
    [% END %]

The PERL block may contain other template directives. These are processed before the Perl code is evaluated.

    [% name = 'Fred Smith' %]
    [% PERL %]
       print "[% name %]\n";
    [% END %]

Thus, the Perl code in the above example is evaluated as:

    print "Fred Smith\n";

Exceptions may be thrown from within PERL blocks via die() and will be correctly caught by enclosing TRY blocks.

    [% TRY %]
       [% PERL %]
          die "nothing to live for\n";
       [% END %]
    [% CATCH %]
       error: [% error.info %]
    [% END %]

output: error: nothing to live for

RAWPERL
The Template Toolkit parser reads a source template and generates the text of a Perl subroutine as output. It then uses eval() to evaluate it into a subroutine reference. This subroutine is then called to process the template, passing a reference to the current Template::Context object through which the functionality of the Template Toolkit can be accessed. The subroutine reference can be cached, allowing the template to be processed repeatedly without requiring any further parsing.

For example, a template such as:

    [% PROCESS header %]
    The [% animal %] sat on the [% location %]
    [% PROCESS footer %]

is converted into the following Perl subroutine definition:

    sub {
        my $context = shift;
        my $stash   = $context->stash;
        my $output  = '';
        my $error;

        eval { BLOCK: {
            $output .=  $context->process('header');
            $output .=  "The ";
            $output .=  $stash->get('animal');
            $output .=  " sat on the ";
            $output .=  $stash->get('location');
            $output .=  $context->process('footer');
            $output .=  "\n";
        } };
        if ($@) {
            $error = $context->catch($@, \$output);
            die $error unless $error->type eq 'return';
        }

        return $output;
    }

To examine the Perl code generated, such as in the above example, set the $Template::Parser::DEBUG package variable to any true value. You can also set the $Template::Directive::PRETTY variable true to have the code formatted in a readable manner for human consumption. The source code for each generated template subroutine will be printed to STDERR on compilation (i.e. the first time a template is used).

    $Template::Parser::DEBUG = 1;
    $Template::Directive::PRETTY = 1;
    ...
    $template->process($file, $vars)
        || die $template->error(), "\n";

The PERL ... END construct allows Perl code to be embedded into a template (when the EVAL_PERL option is set), but it is evaluated at ``runtime'' using eval() each time the template subroutine is called. This is inherently flexible, but not as efficient as it could be, especially in a persistant server environment where a template may be processed many times.

The RAWPERL directive allows you to write Perl code that is integrated directly into the generated Perl subroutine text. It is evaluated once at compile time and is stored in cached form as part of the compiled template subroutine. This makes RAWPERL blocks more efficient than PERL blocks.

The downside is that you must code much closer to the metal. Within PERL blocks, you can call print() to generate some output. RAWPERL blocks don't afford such luxury. The code is inserted directly into the generated subroutine text and should conform to the convention of appending to the '$output' variable.

    [% PROCESS  header %]
    [% RAWPERL %]
       $output .= "Some output\n";
       ...
       $output .= "Some more output\n";
    [% END %]

The critical section of the generated subroutine for this example would then look something like:

    ...
    eval { BLOCK: {
        $output .=  $context->process('header');
        $output .=  "\n";
        $output .= "Some output\n";
        ...
        $output .= "Some more output\n";
        $output .=  "\n";
    } };
    ...

As with PERL blocks, the $context and $stash references are pre-defined and available for use within RAWPERL code.

Exception Handling and Flow Control

TRY / THROW / CATCH / FINAL
The Template Toolkit supports fully functional, nested exception handling. The TRY directive introduces an exception handling scope which continues until the matching END directive. Any errors that occur within that block will be caught and can be handled by one of the CATCH blocks defined.
    [% TRY %]
       ...blah...blah...
       [% CALL somecode %]
       ...etc...
       [% INCLUDE someblock %]
       ...and so on...
    [% CATCH %]
       An error occurred!
    [% END %]

Errors are raised as exceptions (objects of the Template::Exception class) and contain two fields, 'type' and 'info'. The exception 'type' can be any string containing letters, numbers, '_' or '.', and is used to indicate the kind of error that occurred. The 'info' field contains an error message indicating what actually went wrong. Within a catch block, the exception object is aliased to the 'error' variable. You can access the 'type' and 'info' fields directly.

    [% mydsn = 'dbi:MySQL:foobar' %]
    ...
    [% TRY %]
       [% USE DBI(mydsn) %]
    [% CATCH %]
       ERROR! Type: [% error.type %]
              Info: [% error.info %]
    [% END %]

output (assuming a non-existant database called 'foobar'):

    ERROR!  Type: DBI
            Info: Unknown database "foobar"

The 'error' variable can also be specified by itself and will return a string of the form ``$type error - $info''.

    ...
    [% CATCH %]
    ERROR: [% error %]
    [% END %]

output:

    ERROR: DBI error - Unknown database "foobar"

Each CATCH block may be specified with a particular exception type denoting the kind of error that it should catch. Multiple CATCH blocks can be provided to handle different types of exception that may be thrown in the TRY block. A CATCH block specified without any type, as in the previous example, is a default handler which will catch any otherwise uncaught exceptions. This can also be specified as [% CATCH DEFAULT %].

    [% TRY %]
       [% INCLUDE myfile %]
       [% USE DBI(mydsn) %]
       [% CALL somecode %]
       ...
    [% CATCH file %]
       File Error! [% error.info %]
    [% CATCH DBI %]
       [% INCLUDE database/error.html %]
    [% CATCH %]
       [% error %]
    [% END %]

Remember that you can specify multiple directives within a single tag, each delimited by ';'. Thus, you might prefer to write your simple CATCH blocks more succinctly as:

    [% TRY %]
       ...
    [% CATCH file; "File Error! $error.info" %]
    [% CATCH DBI;  INCLUDE database/error.html %]
    [% CATCH; error %]
    [% END %]

or even:

    [% TRY %]
       ...
    [% CATCH file ;
           "File Error! $error.info" ;
       CATCH DBI ;
           INCLUDE database/error.html ;
       CATCH ;
           error ;
       END
    %]

The DBI plugin throws exceptions of the 'DBI' type (in case that wasn't already obvious). The other specific exception caught here is of the 'file' type.

A 'file' error is automatically thrown by the Template Toolkit when it can't find a file, or fails to load, parse or process a file that has been requested by an INCLUDE, PROCESS, INSERT or WRAPPER directive. If 'myfile' can't be found in the example above, the [% INCLUDE myfile %] directive will raise a 'file' exception which is then caught by the [% CATCH file %] block, generating the output:

    File Error! myfile: not found

Note that the DEFAULT option (disabled by default) allows you to specify a default file to be used any time a template file can't be found. This will prevent file exceptions from ever being raised when a non-existant file is requested (unless, of course, the DEFAULT file doesn't exist). Errors encountered once the file has been found (i.e. read error, parse error) will be raised as file exceptions as per usual.

Uncaught exceptions (i.e. the TRY block doesn't have a type specific or default CATCH handler) may be caught by enclosing TRY blocks which can be nested indefinately across multiple templates. If the error isn't caught at any level then processing will stop and the Template process() method will return a false value to the caller. The relevant Template::Exception object can be retrieved by calling the error() method.

    [% TRY %]
       ...
       [% TRY %]
          [% INCLUDE $user.header %]
       [% CATCH file %]
          [% INCLUDE header %]
       [% END %]
       ...
    [% CATCH DBI %]
       [% INCLUDE database/error.html %]
    [% END %]

In this example, the inner TRY block is used to ensure that the first INCLUDE directive works as expected. We're using a variable to provide the name of the template we want to include, user.header, and it's possible this contains the name of a non-existant template, or perhaps one containing invalid template directives. If the INCLUDE fails with a 'file' error then we CATCH it in the inner block and INCLUDE the default 'header' file instead. Any DBI errors that occur within the scope of the outer TRY block will be caught in the relevant CATCH block, causing the 'database/error.html' template to be processed. Note that included templates inherit all currently defined template variable so these error files can quite happily access the 'error' variable to retrieve information about the currently caught exception. e.g.

'database/error.html':

    <h2>Database Error</h2>
    A database error has occurred: [% error.info %]

You can also specify a FINAL block. This is always processed regardless of the outcome of the TRY and/or CATCH block. If an exception is uncaught then the FINAL block is processed before jumping to the enclosing block or returning to the caller.

    [% TRY %]
       ...
    [% CATCH this %] 
       ...
    [% CATCH that %] 
       ...
    [% FINAL %]
       All done!
    [% END %]

The output from the TRY block is left intact up to the point where an exception occurs. For example, this template:

    [% TRY %]
       This gets printed 
       [% THROW food 'carrots' %]
       This doesn't
    [% CATCH food %]
       culinary delights: [% error.info %]
    [% END %]

generates the following output:

    This gets printed
    culinary delights: carrots

The CLEAR directive can be used in a CATCH or FINAL block to clear any output created in the TRY block.

    [% TRY %]
       This gets printed 
       [% THROW food 'carrots' %]
       This doesn't
    [% CATCH food %]
       [% CLEAR %]
       culinary delights: [% error.info %]
    [% END %]

output:

    culinary delights: carrots

Exception types are hierarchical, with each level being separated by
the familiar dot operator.  A 'DBI.connect' exception is a more
specific kind of 'DBI' error.  Similarly, a 'myown.error.barf' is a
more specific kind of 'myown.error' type which itself is also a
'myown' error.  A CATCH handler that specifies a general exception
type (such as 'DBI' or 'myown.error') will also catch more specific
types that have the same prefix as long as a more specific handler
isn't defined.  Note that the order in which CATCH handlers are
defined is irrelevant; a more specific handler will always catch an
exception in preference to a more generic or default one.
    [% TRY %]
       ...
    [% CATCH DBI ;
         INCLUDE database/error.html ;
       CATCH DBI.connect ;
         INCLUDE database/connect.html ;
       CATCH ; 
         INCLUDE error.html ;
       END
    %]

In this example, a 'DBI.connect' error has it's own handler, a more general 'DBI' block is used for all other DBI or DBI.* errors and a default handler catches everything else.

Exceptions can be raised in a template using the THROW directive. The first parameter is the exception type which doesn't need to be quoted (but can be, it's the same as INCLUDE) followed by the relevant error message which can be any regular value such as a quoted string, variable, etc.

    [% THROW food "Missing ingredients: $recipe.error" %]
    [% THROW user.login 'no user id: please login' %]
    [% THROW $myerror.type "My Error: $myerror.info" %]

Exceptions can also be thrown from Perl code which you've bound to template variables, or defined as a plugin or other extension. To raise an exception, call die() passing a reference to a Template::Exception object as the argument. This will then be caught by any enclosing TRY blocks from where the code was called.

    use Template::Exception;
    ...
    my $vars = {
        foo => sub {
            # ... do something ...
            die Template::Exception->new('myerr.naughty',
                                         'Bad, bad error');
        },
    };

template:

    [% TRY %]
       ...
       [% foo %]
       ...   
    [% CATCH myerr ;
         "Error: $error" ;
       END
    %]

output:

    Error: myerr.naughty error - Bad, bad error

You can also call die() with a single string, as is common in much existing Perl code. This will automatically be converted to an exception of the 'undef' type (that's the literal string 'undef', not the undefined value). If the string isn't terminated with a newline then Perl will append the familiar `` at $file line $line'' message.

    sub foo {
        # ... do something ...
        die "I'm sorry, Dave, I can't do that\n";
    }

If you're writing a plugin, or some extension code that has the current Template::Context in scope (you can safely skip this section if this means nothing to you) then you can also raise an exception by calling the context throw() method. You can pass it an Template::Exception object reference, a pair of ($type, $info) parameters or just an $info string to create an exception of 'undef' type.

    $context->throw($e);            # exception object
    $context->throw('Denied');      # 'undef' type
    $context->throw('user.passwd', 'Bad Password');

NEXT
The NEXT directive can be used to start the next iteration of a FOREACH or WHILE loop.
    [% FOREACH user = userlist %]
       [% NEXT IF user.isguest %]
       Name: [% user.name %]    Email: [% user.email %]
    [% END %]

LAST
The LAST directive can be used to prematurely exit a FOREACH or WHILE loop.
    [% FOREACH user = userlist %]
       Name: [% user.name %]    Email: [% user.email %]
       [% LAST IF some.condition %]
    [% END %]

BREAK can also be used as an alias for LAST.

RETURN
The RETURN directive can be used to stop processing the current template and return to the template from which it was called, resuming processing at the point immediately after the INCLUDE, PROCESS or WRAPPER directive. If there is no enclosing template then the Template process() method will return to the calling code with a true value.
    Before
    [% INCLUDE half_wit %]
    After

    [% BLOCK half_wit %]
    This is just half...
    [% RETURN %]
    ...a complete block
    [% END %]

output:

    Before
    This is just half...
    After

STOP
The STOP directive can be used to indicate that the processor should stop gracefully without processing any more of the template document. This is a planned stop and the Template process() method will return a true value to the caller. This indicates that the template was processed successfully according to the directives within it.
    [% IF something.terrible.happened %]
       [% INCLUDE fatal/error.html %]
       [% STOP %]
    [% END %]
    [% TRY %]
       [% USE DBI(mydsn) %]
       ...
    [% CATCH DBI.connect %]
       <p>Cannot connect to the database: [% error.info %]</p>
       <br>
       We apologise for the inconvenience.  The cleaning lady 
       has removed the server power to plug in her vacuum cleaner.
       Please try again later.
       </p>
       [% INCLUDE footer %]
       [% STOP %]
    [% END %]

CLEAR
The CLEAR directive can be used to clear the output buffer for the current enclosing block. It is most commonly used to clear the output generated from a TRY block up to the point where the error occurred.
    [% TRY %]
       blah blah blah            # this is normally left intact
       [% THROW some 'error' %]  # up to the point of error
       ...
    [% CATCH %]
       [% CLEAR %]               # clear the TRY output
       [% error %]               # print error string
    [% END %]

Miscellaneous

META
The META directive allows simple metadata items to be defined within a template. These are evaluated when the template is parsed and as such may only contain simple values (e.g. it's not possible to interpolate other variables values into META variables).
    [% META
       title   = 'The Cat in the Hat'
       author  = 'Dr. Seuss'
       version = 1.23 
    %]

The 'template' variable contains a reference to the main template being processed. These metadata items may be retrieved as attributes of the template.

    <h1>[% template.title %]</h1>
    <h2>[% template.author %]</h2>

The 'name' and 'modtime' metadata items are automatically defined for each template to contain its name and modification time in seconds since the epoch.

    [% USE date %]              # use Date plugin to format time
    ...
    [% template.name %] last modified
    at [% date.format(template.modtime) %]

The PRE_PROCESS and POST_PROCESS options allow common headers and footers to be added to all templates. The 'template' reference is correctly defined when these templates are processed, allowing headers and footers to reference metadata items from the main template.

    $template = Template->new({
        PRE_PROCESS  => 'header',
        POST_PROCESS => 'footer',
    });
    $template->process('cat_in_hat');

header: <html> <head> <title>[% template.title %]</title> </head> <body>

cat_in_hat: [% META title = 'The Cat in the Hat' author = 'Dr. Seuss' version = 1.23 year = 2000 %]

    The cat in the hat sat on the mat.

footer: <hr> &copy; [% template.year %] [% template.author %] </body> </html>

The output generated from the above example is:


    <html>
    <head>
    <title>The Cat in the Hat</title>
    </head>
    <body>
    The cat in the hat sat on the mat.
    <hr>
    &copy; 2000 Dr. Seuss
    </body>
    </html>

TAGS
The TAGS directive can be used to set the START_TAG and END_TAG values on a per-template file basis.
    [% TAGS <+ +> %]
    <+ INCLUDE header +>

The TAGS directive may also be used to set a named TAG_STYLE

    [% TAGS html %]
    <!-- INCLUDE header -->

See the TAGS and TAG_STYLE configuration options for further details.


CONFIGURATION OPTIONS

The Template module accepts configuration items destined for any other Template::* module that it may create and will forward them appropriately. The following list summarises the various options under several broad categories.

Template Style and Parsing Options

START_TAG, END_TAG
The START_TAG and END_TAG options are used to specify character sequences or regular expressions that mark the start and end of a template directive. The default values for START_TAG and END_TAG are '[%' and '%]' respectively, giving us the familiar directive style:
    [% example %]

Any Perl regex characters can be used and therefore should be escaped (or use the Perl quotemeta function) if they are intended to represent literal characters.

    my $template = Template->new({ 
        START_TAG => quotemeta('<+'),
        END_TAG   => quotemeta('+>'),
    });

example:

    <+ INCLUDE foobar +>

The TAGS directive can also be used to set the START_TAG and END_TAG values on a per-template file basis.

    [% TAGS <+ +> %]

TAG_STYLE
The TAG_STYLE option can be used to set both START_TAG and END_TAG according to pre-defined tag styles.
    my $template = Template->new({ 
        TAG_STYLE => 'php',
    });

Available styles are:

    template    [% ... %]               (default)
    template1   [% ... %] or %% ... %%  (Template version 1)
    metatext    %% ... %%               (Text::MetaText)
    php         <? ... ?>               (PHP)
    asp         <% ... %>               (ASP)
    mason       <% ...  >               (HTML::Mason)
    html        <!-- ... -->            (HTML comments)

Any values specified for START_TAG and/or END_TAG will over-ride those defined by a TAG_STYLE.

The TAGS directive may also be used to set a TAG_STYLE

    [% TAGS html %]
    <!-- INCLUDE header -->

PRE_CHOMP, POST_CHOMP
Anything outside a directive tag is considered plain text and is generally passed through unaltered (but see the INTERPOLATE option). This includes all whitespace and newlines characters surrounding directive tags. Directives that don't generate any output will leave gaps in the output document.

Example:

    Foo
    [% a = 10 %]
    Bar

Output:

    Foo
    Bar

The PRE_CHOMP and POST_CHOMP options can help to clean up some of this extraneous whitespace. Both are disabled by default.

    my $template = Template->new({
        PRE_CHOMP  => 1,
        POST_CHOMP => 1,
    });

With PRE_CHOMP set true, the newline and whitespace preceeding a directive at the start of a line will be deleted. This has the effect of concatenating a line that starts with a directive onto the end of the previous line.

        Foo <----------.
                       |
    ,---(PRE_CHOMP)----'
    |
    `-- [% a = 10 %] --.
                       |
    ,---(POST_CHOMP)---'
    |
    `-> Bar

With POST_CHOMP set true, any whitespace after a directive up to and including the newline will be deleted. This has the effect of joining a line that ends with a directive onto the start of the next line.

PRE_CHOMP and POST_CHOMP can be activated for individual directives by placing a '-' immediately at the start and/or end of the directive.

    [% FOREACH user = userlist %]
       [%- user -%]
    [% END %]

The '-' characters activate both PRE_CHOMP and POST_CHOMP for the one directive '[%- name -%]'. Thus, the template will be processed as if written:

    [% FOREACH user = userlist %][% user %][% END %]

Similarly, '+' characters can be used to disable PRE_CHOMP or POST_CHOMP (i.e. leave the whitespace/newline intact) options on a per