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.

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 (2.718), 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.

You can concatenate strings together using the ' _ ' operator. In Perl 5, the . is used for string concatenation, but in Perl 6, as in the Template Toolkit, the . will be used as the method calling operator and ' _ ' will be used for string concatenation. Note that the operator must be specified with surrounding whitespace which, as Larry says, is construed as a feature:

[% copyright = '(C) Copyright' _ year _ ' ' _ author %]

You can, of course, achieve a similar effect with double quoted string interpolation.

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.

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.

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.

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 $ or double-quoted

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 ignored 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.

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.

You can specify dotted variables as "local" variables to an INCLUDE directive. However, be aware that because of the localisation issues explained above (if you skipped the previous Technical Note above then you might want to go back and read it or skip this section too), the variables might not actualy be "local". If the first element of the variable name already references a hash array then the variable update will affect the original variable.

This behaviour can be a little unpredictable (and may well be improved upon in a future version). If you know what you're doing with it and you're sure that the variables in question are defined (nor not) as you expect them to be, then you can rely on this feature to implement some powerful "global" data sharing techniques. Otherwise, you might prefer to steer well clear and always pass simple (undotted) variables as parameters to INCLUDE and other similar directives.

If you want to process several templates in one go then you can specify each of their names (quoted or unquoted names only, no unquoted $variables) joined together by +. The INCLUDE directive will then process them in order.

The variable stash is localised once and then the templates specified are processed in order, all within that same variable context. This makes it slightly faster than specifying several separate INCLUDE directives (because you only clone the variable stash once instead of n times), but not quite as "safe" because any variable changes in the first file will be visible in the second, third and so on. This might be what you want, of course, but then again, it might not.

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.

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:

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:

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

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

[% INSERT legalese.txt WRAPPER big_bold_table %]

It's also possible to specify multiple templates to a WRAPPER directive. The specification order indicates outermost to innermost wrapper templates. For example, given the following template block definitions:

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.

The and, or and not operator are provided as aliases for &&, || and !, respectively. Unlike Perl, which treats and, or and not as separate, lower-precedence versions of the other operators, the Template Toolkit performs a straightforward substitution of and for &&, and so on. That means that and, or and not have the same operator precedence as &&, || and !.

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.

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.

However, under normal operation, the loop variable remains in scope after the FOREACH loop has ended (caveat: overwriting any variable previously in scope). This is useful as the loop variable is secretly an iterator object (see below) and can be used to analyse the last entry processed by the loop.

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.

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

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.

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.

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:

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:

The FILTERS option, described in Template::Manual::Config, allows custom filters to be defined when a Template object is instantiated. The 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.

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.

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.

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.

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 Template::Plugin.

A number of standard plugins are included with the Template Toolkit (see below and Template::Manual::Plugins). The names of these standard plugins are case insensitive.

The recommended convention is to specify these plugin names in lower case. The Template Toolkit first looks for an exact case-sensitive match and then tries the lower case conversion of the name specified.

[% USE Foo %] # look for 'Foo' then 'foo'

If you define all your PLUGINS with lower case names then they will be located regardless of how the user specifies the name in the USE directive. If, on the other hand, you define your PLUGINS with upper or mixed case names then the name specified in the USE directive must match the case exactly.

If the plugin isn't defined in either the standard plugins ($Template::Plugins::STD_PLUGINS) or via the PLUGINS option, then the PLUGIN_BASE is searched.

In this case the plugin name is case-sensitive. It is appended to each of the PLUGIN_BASE module namespaces in turn (default: Template::Plugin) to construct a full module name which it attempts to locate and load. Any periods, '.', in the name will be converted to '::'.

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.

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 passed as the first parameter.

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

equivalent to:

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

The only exception to this is when a module is loaded via the LOAD_PERL option. In this case the $context reference is not passed to the new() constructor. This is based on the assumption that the module is a regular Perl module rather than a Template Toolkit plugin so isn't expecting a context reference and wouldn't know what to do with it anyway.

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.

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:

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().

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

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 Template::Context 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 Template::Stash for further details.

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.

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).

The PERL ... END construct allows Perl code to be embedded into a template when the EVAL_PERL option is set. 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 persistent 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. For example, in a PERL block 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.

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.

Errors are raised as exceptions (objects of the Template::Exception class) which contain two fields: type and info. The exception type is used to indicate the kind of error that occurred. It is a simple text string which can contain letters, numbers, '_' or '.'. 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.

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 %].

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 exception 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. The output generated would be:

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 your specify 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. if the TRY block doesn't have a type specific or default CATCH handler) may be caught by enclosing TRY blocks which can be nested indefinitely 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.

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. For example, the database/error.html template might look like this:

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

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, an example.error.barf is a more specific kind of example.error type which itself is also a example error.

A CATCH handler that specifies a general exception type (such as DBI or example.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.

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.

In addition to specifying individual positional arguments as [% error.info.args.n %], the info hash contains keys directly pointing to the positional arguments, as a convenient shortcut.

[% error.info.0 %] # same as [% error.info.args.0 %]

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.

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.

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.

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 %]

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.

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.

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).

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.

The DEBUG directive can be used to enable or disable directive debug messages within a template. The DEBUG configuration option must be set to include DEBUG_DIRS for the DEBUG directives to have any effect. If DEBUG_DIRS is not set then the parser will automatically ignore and remove any DEBUG directives.

The DEBUG directive can be used with an on or off parameter to enable or disable directive debugging messages from that point forward. When enabled, the output of each directive in the generated output will be prefixed by a comment indicate the file, line and original directive text.

[% DEBUG on %]
directive debugging is on (assuming DEBUG option is set true)
[% DEBUG off %]
directive debugging is off

The format parameter can be used to change the format of the debugging message.