perldoc > Template::Manual::Directives

๐Ÿ“ NAME

Template::Manual::Directives - Template directives

๐Ÿš€ Quick Reference

Use CaseCommandDescription
๐Ÿ“ฅ Output variable value[% variable %] or [% GET variable %]Print the value of a variable
๐Ÿ“ž Call a subroutine without output[% CALL sub %]Execute a subroutine, discard result
๐Ÿ› ๏ธ Assign a variable[% SET var = value %]Set a variable to a literal or expression
๐Ÿ”„ Default value for undefined[% DEFAULT var = value %]Set variable only if not already true
๐Ÿ“‚ Insert raw file[% INSERT file %]Insert file contents without processing
๐Ÿ“Ž Include and process template[% INCLUDE template %]Process template with localised variables
โš™๏ธ Process template without localisation[% PROCESS template %]Faster, but variables persist
๐ŸŽ Wrap content in template[% WRAPPER template %] ... [% END %]Pass inner output as content variable
๐Ÿงฑ Define a reusable block[% BLOCK name %] ... [% END %]Define a template component
โ“ Conditional execution[% IF condition %] ... [% END %]Conditionally process block
๐Ÿ”€ Multi-way condition[% SWITCH var %] [% CASE val %] ... [% END %]Switch/case construct
๐Ÿ” Loop over list[% FOREACH item IN list %] ... [% END %]Iterate over list or hash
๐Ÿ”„ Loop while condition true[% WHILE condition %] ... [% END %]Loop until condition false
๐ŸŽจ Apply filter to output[% FILTER filter %] ... [% END %]Post-process block output
๐Ÿ“ฆ Load a plugin[% USE plugin %]Load and instantiate a plugin module
๐Ÿ“ Define a macro[% MACRO name(params) directive %]Define a shorthand directive
๐Ÿช Embed Perl code[% PERL %] ... [% END %] (requires EVAL_PERL)Execute Perl code
โšก Embed raw Perl in compiled code[% RAWPERL %] ... [% END %]Efficient Perl integration
๐Ÿšจ Exception handling[% TRY %] ... [% CATCH type %] ... [% END %]Try/catch exception handling
โญ๏ธ Next loop iteration[% NEXT %]Skip to next iteration
โน๏ธ Exit loop[% LAST %] or [% BREAK %]Exit FOREACH/WHILE loop
โ†ฉ๏ธ Return from template[% RETURN %]Stop processing current template
๐Ÿ›‘ Stop processing[% STOP %]Gracefully stop template processing
๐Ÿงน Clear output buffer[% CLEAR %]Clear output from TRY block
๐Ÿ“‹ Set metadata[% META key = value %]Define template metadata
๐Ÿท๏ธ Change tag markers[% TAGS start end %]Set custom tag delimiters
๐Ÿ› Enable debug output[% DEBUG on %]Toggle directive debugging

๐Ÿ”ง 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 can have an unlimited number of elements, each separated by a dot. Each element can have arguments specified within parentheses.

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

See Template::Manual::Variables for a full discussion on template variables.

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.

[% 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. Useful for calling subroutines or object methods.

[% 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 (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.

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

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

Simple expressions can also be used.

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

You can concatenate strings together using the _ operator.

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

Alternatively, use double quoted string interpolation.

[% copyright = "(C) Copyright $year $author" %]

๐Ÿ”„ 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'
%]

Useful in common template components to ensure sensible defaults.

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

๐Ÿ“„ Processing Template Files and Blocks

๐Ÿ“‚ INSERT

The INSERT directive is used to insert the contents of an external file at the current position. No parsing or processing is performed.

[% INSERT myfile %]

The filename should be relative to one of the INCLUDE_PATH directories. Absolute or relative filenames require ABSOLUTE and RELATIVE options.

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

$template->process('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, 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

Multiple files can be specified using + as a delimiter.

[% INSERT legalese.txt + warning.txt %]
[% INSERT  "$legalese" + warning.txt %]  # requires quoting

๐Ÿ“Ž 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 parent template, 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 visible, the template name should be a file relative to one of the INCLUDE_PATH directories. The INCLUDE directive automatically quotes the filename. When a variable contains the name, prefix with $ or double-quote.

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

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

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

Local variable definitions may be specified after the template name, temporarily masking any existing variables.

[% INCLUDE table %]

[% INCLUDE table title="Active Projects" %]

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

The INCLUDE directive localises (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 %]
foo is originally 10
   foo was 10
   foo is now 20
foo is still 10

Technical Note: the localisation of the stash is only skin deep. The top-level variable namespace is copied, but no deep-copy of other structures is performed. Therefore, updating compound variables (e.g. foo.bar) will change the original copy. Use PROCESS for faster execution without localisation if you're not worried about preserving variable values.

You can specify dotted variables as local variables to an INCLUDE directive. However, due to the localisation issues, the variables might not actually be local if the first element already references a hash array.

[% foo = {
       bar = 'Baz'
   }
%]

[% INCLUDE somefile foo.bar='Boz' %]

[% foo.bar %]           # Boz

To process several templates at once, specify each name joined by +. The variable stash is localised once.

[% INCLUDE html/header + "site/$header" + site/menu
     title = "My Groovy Web Site"
%]

โš™๏ธ 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 %]
foo is 10
   changed foo to 20
foo is 20

Parameters may be specified and 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 %]
foo is 10
   this is bar, foo is 20
foo is 20

The PROCESS directive is slightly faster than INCLUDE because it avoids localising the variable stash. 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 interpolate a variable for the template name.

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

Multiple templates can be specified, delimited by +.

[% PROCESS html/header + my/header %]

๐ŸŽ WRAPPER

The WRAPPER directive 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, with outermost to innermost order.

[% BLOCK bold   %]<b>[% content %]</b>[% END %]
[% BLOCK italic %]<i>[% content %]</i>[% END %]
[% WRAPPER bold+italic %]Hello World[% END %]
<b><i>Hello World</i></b>

๐Ÿงฑ 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 %]

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

[% MACRO locate BLOCK %]
   The [% animal %] sat on the [% place %].
[% END %]

[% locate(animal='cat', place='mat') %]    # The cat sat on the mat
[% locate(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 %]

The and, or and not operator are provided as aliases for &&, || and !, respectively. They have the same operator precedence.

๐Ÿ”€ SWITCH / CASE

The SWITCH / CASE construct can be used to perform a multi-way conditional test.

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

[% foo   = 'Foo'
   items = [ 'one', 'two', 'three' ]
%]

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

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

Stuff:
[% stuff = [ foo "$foo Bar" ] %]
[% FOREACH s IN stuff %]
   * [% s %]
[% END %]
Things:
  * Foo
  * Bar
  * Foo Baz

Items:
  * one
  * two
  * three

Stuff:
  * Foo
  * Foo Bar

You can use also use = instead of IN if you prefer.

[% FOREACH i = items %]

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 IN userlist %]
   [% user.id %] [% user.name %]
[% END %]

short form:

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

Note: This usage creates a localised variable context to prevent imported hash keys from overwriting existing variables. The imported definitions and any other variables defined in such a FOREACH loop will be lost at the end of the loop.

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

[% users = {
     tom   => 'Thomas',
     dick  => 'Richard',
     larry => 'Lawrence',
   }
%]

[% FOREACH u IN users %]
   * [% u.key %] : [% u.value %]
[% END %]
   * dick : Richard
   * larry : Lawrence
   * tom : Thomas

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

[% FOREACH user IN 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 IN 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:

See Template::Iterator for further details.

Example:

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

Nested loops will work as expected, with the loop variable correctly referencing the innermost loop.

[% FOREACH group IN grouplist;
     # loop => group iterator
     "Groups:\n" IF loop.first;

     FOREACH user IN group.userlist;
        # loop => user iterator
        "$loop.count: $user.name\n";
     END;

     # loop => group iterator
     "End of Groups\n" IF loop.last;
   END
%]

The iterator plugin can also be used to explicitly create an iterator object. See Template::Plugin::Iterator for further details.

[% USE giter = iterator(grouplist) %]

[% FOREACH group IN giter %]
   [% FOREACH user IN group.userlist %]
         user #[% loop.count %] in
         group [% giter.count %] is
         named [% 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. If the loop exceeds 1000 iterations then an undef exception will be thrown.

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. The html filter, for example, escapes the <, > and & characters.

[% FILTER html %]
   HTML text may have < and > characters embedded
   which you want converted to the correct HTML entities.
[% END %]
   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.

[% INCLUDE mytext FILTER html FILTER html_para %]

or

[% INCLUDE mytext | html | html_para %]

Filters come in two flavours: static and dynamic. A static filter is a simple subroutine which accepts a text string and returns the modified text. Dynamic filters can accept arguments when called. The repeat filter is an example of a dynamic filter.

[% FILTER repeat(3) %]blah [% END %]
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, and should return a subroutine reference that implements the filter.

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.

[% FILTER echo = repeat(2) %]
Is there anybody out there?
[% END %]

[% FILTER echo %]
Mother, should I build a wall?
[% END %]
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, 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. 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 returns another subroutine reference.

my $vars = {
    myfilter => sub { \&my_filter_sub },
};

sub my_filter_sub {
    my $text = shift;
    # do something
    return $text;
}
[% FILTER $myfilter %]
   ...
[% END %]

Alternately, you can bless a subroutine reference into a class to fool the Template Toolkit into thinking it's an object.

my $vars = {
    myfilter => bless(\&my_filter_sub, 'anything_you_like'),
};
[% FILTER $myfilter %]
   ...
[% END %]

Filters bound to template variables remain local to the variable context in which they are defined. If you want to define a filter which persists for the lifetime of the processor, call the define_filter() method on the current Template::Context object.

See Template::Manual::Filters for a complete list of available filters.

๐Ÿ“ฆ 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, consult Template::Plugin.

A number of standard plugins are included with the Template Toolkit. The names of these standard plugins are case insensitive.

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

You can also define further plugins using the PLUGINS option.

my $tt = Template->new({
    PLUGINS => {
        foo => 'My::Plugin::Foo',
        bar => 'My::Plugin::Bar',
    },
});

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

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

If the plugin isn't defined in either the standard plugins or via the PLUGINS option, then the PLUGIN_BASE is searched. In this case the plugin name is case-sensitive.

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

The LOAD_PERL option (disabled by default) provides a further way by which external Perl modules may be loaded. If a regular Perl module supports an object-oriented interface and a new() constructor, it can be loaded and instantiated automatically.

[% USE file = IO.File('/tmp/mydata') %]

[% WHILE (line = file.getline) %]
   <!-- [% line %] -->
[% END %]

Any additional parameters supplied in parenthesis after the plugin name will 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 is when a module is loaded via the LOAD_PERL option. In this case the $context reference is not passed to the new() constructor.

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

[% 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. Methods can be called on the object.

[% USE table(mydata, rows=3) %]

[% FOREACH row IN table.rows %]
   <tr>
   [% FOREACH item IN row %]
    <td>[% item %]</td>
   [% END %]
   </tr>
[% END %]

An alternative name may be provided for the plugin.

[% USE scores = table(myscores, cols=5) %]

[% FOREACH row IN scores.rows %]
   ...
[% END %]

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

[% USE mycgi = URL('/cgi-bin/foo.pl', debug=1) %]
<a href="[% mycgi %]">...
<a href="[% mycgi(mode='submit') %]"...>
<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. All of the methods provided by the CGI module 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
%]

See Template::Manual::Plugins for more information.

๐Ÿ“ 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.

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

equivalent to:

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

A MACRO definition may include parameter names.

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

Here's another example, defining a macro for display numbers in comma-delimited groups of 3.

[% MACRO number(n) GET n.chunk(-3).join(',') %]
[% number(1234567) %]    # 1,234,567

A MACRO may precede 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.

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

[% header %]

If you've got the EVAL_PERL option set, you can even define a MACRO as a PERL block.

[% MACRO triple(n) PERL %]
     my $n = $stash->get('n');
     print $n * 3;
[% END -%]

๐Ÿช PERL

(for the advanced reader)

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.

Perl code is evaluated in the Template::Perl package. The $context package variable contains a reference to the current Template::Context object.

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

The $stash variable contains a reference to the top-level stash object which manages template variables.

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

Output is generated from the PERL block by calling print(). Note that the Template::Perl::PERLOUT handle is selected 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 using die(). They will be correctly caught by enclosing TRY blocks.

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

โšก RAWPERL

(for the very advanced reader)

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

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

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.

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

(more advanced material)

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) which contain two fields: type and info. The exception type is used to indicate the kind of error that occurred. The info field contains an error message. Within a catch block, the exception object is aliased to the error variable.

[% mydsn = 'dbi:MySQL:foobar' %]
...

[% TRY %]
   [% USE DBI(mydsn) %]
[% CATCH %]
   ERROR! Type: [% error.type %]
          Info: [% error.info %]
[% END %]
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 %]
ERROR: DBI error - Unknown database "foobar"

Each CATCH block may be specified with a particular exception type. Multiple CATCH blocks can be provided to handle different exception types. A CATCH block specified without any type is a default handler. 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 ;.

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

The DBI plugin throws exceptions of the DBI type. The 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.

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-existent file is requested.

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

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.

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

[% TRY %]
   This gets printed
   [% THROW food 'carrots' %]
   This doesn't
[% CATCH food %]
   culinary delights: [% error.info %]
[% END %]
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 %]
culinary delights: carrots

Exception types are hierarchical, with each level being separated by the dot operator. A DBI.connect exception is a more specific kind of DBI error. A CATCH handler that specifies a general exception type will also catch more specific types that have the same prefix as long as a more specific handler isn't defined.

[% TRY %]
   ...
[% CATCH DBI ;
     INCLUDE database/error.html ;
   CATCH DBI.connect ;
     INCLUDE database/connect.html ;
   CATCH ;
     INCLUDE error.html ;
   END
%]

Exceptions can be raised in a template using the THROW directive.

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

It's also possible to specify additional positional or named parameters to the THROW directive.

[% THROW food 'eggs' 'flour' msg='Missing Ingredients' %]

In this case, the error info field will be a hash array containing the named arguments and an args item.

type => 'food',
info => {
    msg  => 'Missing Ingredients',
    args => ['eggs', 'flour'],
}

In addition to specifying individual positional arguments, the info hash contains keys directly pointing to the positional arguments.

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

Exceptions can also be thrown from Perl code. To raise an exception, call die() passing a reference to a Template::Exception object.

use Template::Exception;
...
my $vars = {
    foo => sub {
        # ... do something ...
        die Template::Exception->new('myerr.naughty',
                                     'Bad, bad error');
    },
};
[% TRY %]
   [% foo %]
[% CATCH myerr ;
     "Error: $error" ;
   END
%]
Error: myerr.naughty error - Bad, bad error

The info field can also be a reference to another object or data structure.

die Template::Exception->new('myerror', {
    module => 'foo.pl',
    errors => [ 'bad permissions', 'naughty boy' ],
});
[% TRY %]
   ...
[% CATCH myerror %]
   [% error.info.errors.size or 'no';
      error.info.errors.size == 1 ? ' error' : ' errors' %]
   in [% error.info.module %]:
      [% error.info.errors.join(', ') %].
[% END %]
   2 errors in foo.pl:
      bad permissions, naughty boy.

You can also call die() with a single string. This will automatically be converted to an exception of the undef type.

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

If you're writing a plugin or extension code that has the current Template::Context in scope, you can also raise an exception by calling the context throw() method.

$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 IN users %]
   [% 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. BREAK can also be used as an alias for LAST.

[% FOREACH user IN users %]
   Name: [% user.name %]    Email: [% user.email %]
   [% LAST IF some.condition %]
[% END %]

โ†ฉ๏ธ 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 %]
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.

[% IF something.terrible.happened %]
   [% INCLUDE fatal/error.html %]
   [% STOP %]
[% END %]

[% TRY %]
   [% USE DBI(mydsn) %]
   ...
[% CATCH DBI.connect %]
   <h1>Cannot connect to the database: [% error.info %]</h1>
   <p>
     We apologise for the inconvenience.
   </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.

[% 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');
<html>
  <head>
    <title>[% template.title %]</title>
  </head>
  <body>

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

    The cat in the hat sat on the mat.

    <hr>
    &copy; [% template.year %] [% template.author %]
  </body>
</html>
<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.

๐Ÿ› DEBUG

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.

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

[% DEBUG format '<!-- $file line $line : [% $text %] -->' %]
Template::Manual::Directives
๐Ÿ“ NAME ๐Ÿš€ Quick Reference ๐Ÿ”ง Accessing and Updating Template Variables
๐Ÿ“ฅ GET ๐Ÿ“ž CALL ๐Ÿ› ๏ธ SET ๐Ÿ”„ DEFAULT
๐Ÿ“„ Processing Template Files and Blocks
๐Ÿ“‚ INSERT ๐Ÿ“Ž INCLUDE โš™๏ธ PROCESS ๐ŸŽ WRAPPER ๐Ÿงฑ BLOCK
๐Ÿ”€ Conditional Processing
โ“ IF / UNLESS / ELSIF / ELSE ๐Ÿ”€ SWITCH / CASE
๐Ÿ”„ Loop Processing
๐Ÿ” FOREACH ๐Ÿ”„ WHILE
๐Ÿ”ง Filters, Plugins, Macros and Perl
๐ŸŽจ FILTER ๐Ÿ“ฆ USE ๐Ÿ“ MACRO ๐Ÿช PERL โšก RAWPERL
โš ๏ธ Exception Handling and Flow Control
๐Ÿšจ TRY / THROW / CATCH / FINAL โญ๏ธ NEXT โน๏ธ LAST โ†ฉ๏ธ RETURN ๐Ÿ›‘ STOP ๐Ÿงน CLEAR
๐Ÿ› ๏ธ Miscellaneous
๐Ÿ“‹ META ๐Ÿท๏ธ TAGS ๐Ÿ› DEBUG

Generated by phpman v4.9.26-5-g7740029 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-08-23 01:46 @216.73.216.102
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!

^_top_^