).
[% template.title or default.title %]
[% score * 100 %]
[% order.nitems ? checkout(order.total) : 'no items' %]
The C
operator returns the integer result of division. Both C<%> and
C
return the modulus (i.e. remainder) of division.
[% 15 / 6 %] # 2.5
[% 15 div 6 %] # 2
[% 15 mod 6 %] # 3
=head2 CALL
The C directive is similar to C 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) %]
=head2 SET
The C directive allows you to assign new values to existing variables
or create new temporary variables.
[% SET title = 'Hello World' %]
The C 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 C<$>, 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 C.
[% 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 C<'_'> underscore operator. In Perl 5,
the C<.> dot is used for string concatenation, but in Perl 6, as in the Template
Toolkit, the C<.> dot will be used as the method calling operator and C<'_'> underscore 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.
[% copyright = "(C) Copyright $year $author" %]
=head2 DEFAULT
The C directive is similar to C 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'
%]
[% title %]
...etc...
=head1 Processing Template Files and Blocks
=head2 INSERT
The C 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 C
directories. Absolute (i.e. starting with C>) and relative
(i.e. starting with C<.>) filenames may be used if the C and
C options are set, respectively. Both these options are
disabled by default.
my $template = Template->new({
INCLUDE_PATH => '/here:/there',
});
$template->process('myfile');
F:
[% 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 C<$> 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 C<+> as a delimiter. All files
should be unquoted names or quoted strings. Any variables should be
interpolated into double-quoted strings.
[% INSERT legalese.txt + warning.txt %]
[% INSERT "$legalese" + warning.txt %] # requires quoting
=head2 INCLUDE
The C directive is used to process and include the output of
another template file or block.
[% INCLUDE header %]
If a C 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 %]
[% END %]
If a C definition is not currently visible then the template name
should be a file relative to one of the C directories, or
an absolute or relative file name if the C/C options are
appropriately enabled. The C directive automatically quotes the
filename specified, as per C described above. When a variable
contains the name of the template for the C directive, it should
be explicitly prefixed by C<$> or double-quoted
[% 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
accordingly. All variables currently defined will be visible and
accessible from within the included template.
[% title = 'Hello World' %]
[% INCLUDE header %]
...
F:
[% title %]
output:
Hello World
...
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.
[% INCLUDE table %]
[% INCLUDE table title="Active Projects" %]
[% INCLUDE table
title = "Active Projects"
bgcolor = "#80ff00" # chartreuse
border = 2
%]
The C 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 C 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 C
variable referencing a hash will be copied to create a new C
variable but which points to the same hash array. Thus, if you update
compound variables (e.g. C) 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 C directive which is
faster by virtue of not performing any localisation.
You can specify dotted variables as "local" variables to an C 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 actually be
"local". If the first element of the variable name already references a hash
array then the variable update will affect the original variable.
[% foo = {
bar = 'Baz'
}
%]
[% INCLUDE somefile foo.bar='Boz' %]
[% foo.bar %] # Boz
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 C 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
C<$variables>) joined together by C<+>. The C directive
will then process them in order.
[% INCLUDE html/header + "site/$header" + site/menu
title = "My Groovy Web Site"
%]
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 C
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.
=head2 PROCESS
The PROCESS directive is similar to C 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 C 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 C directive is slightly faster than C because it
avoids the need to localise (i.e. copy) the variable stash before
processing the template. As with C and C, the first
parameter does not need to be quoted as long as it contains only
alphanumeric characters, underscores, periods or forward slashes.
A C<$> 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'
As with C, multiple templates can be specified, delimited by
C<+>, and are processed in order.
[% PROCESS html/header + my/header %]
=head2 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:
[% title %]
section/footer:
The C directive provides a way of simplifying this a little. It
encloses a block up to a matching C directive, which is first processed
to generate some output. This is then passed to the named template file or
C as the C 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:
[% title %]
[% content %]
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 C directive.
The specification order indicates outermost to innermost wrapper templates.
For example, given the following template block definitions:
[% BLOCK bold %][% content %][% END %]
[% BLOCK italic %][% content %][% END %]
the directive
[% WRAPPER bold+italic %]Hello World[% END %]
would generate the following output:
Hello World
=head2 BLOCK
The C...C construct can be used to define template component
blocks which can be processed with the C, C and C
directives.
[% BLOCK tabrow %]
[% name %] |
| [% email %] |
[% END %]
[% PROCESS tabrow name='Fred' email='fred@nowhere.com' %]
[% PROCESS tabrow name='Alan' email='alan@nowhere.com' %]
A C 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 C 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 C.
Anonymous Cs 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
=head1 Conditional Processing
=head2 IF / UNLESS / ELSIF / ELSE
The C and C 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 C and/or C 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 C, C and C operator are provided as aliases for
C<&&>, C<||> and C, respectively. Unlike Perl, which treats
C, C and C as separate, lower-precedence versions of the
other operators, the Template Toolkit performs a straightforward substitution
of C for C<&&>, and so on. That means that C, C and C
have the same operator precedence as C<&&>, C<||> and C.
=head2 SWITCH / CASE
The C / C construct can be used to perform a multi-way
conditional test. The C directive expects an expression which is
first evaluated and then compared against each CASE statement in turn.
Each C directive should contain a single value or a list of values
which should match. C may also be left blank or written as
C<[% CASE DEFAULT %]> to specify a default match. Only one C matches,
there is no drop-through between C statements.
[% SWITCH myvar %]
[% CASE 'value1' %]
...
[% CASE ['value2', 'value3'] %] # multiple values
...
[% CASE myhash.keys %] # ditto
...
[% CASE %] # default
...
[% END %]
=head1 Loop Processing
=head2 FOREACH
The C 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 %]
output:
Things:
* Foo
* Bar
* Foo Baz
Items:
* one
* two
* three
Stuff:
* Foo
* Foo Bar
You can use also use C<=> instead of C if you prefer.
[% FOREACH i = items %]
When the C 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 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 C 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 C 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 C 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 %]
Output:
* dick : Richard
* larry : Lawrence
* tom : Thomas
The C directive starts the next iteration in the C loop.
[% FOREACH user IN userlist %]
[% NEXT IF user.isguest %]
Name: [% user.name %] Email: [% user.email %]
[% END %]
The C directive can be used to prematurely exit the loop. C is
also provided as an alias for C.
[% FOREACH match IN results.nsort('score').reverse %]
[% LAST IF match.score < 50 %]
[% match.score %] : [% match.url %]
[% END %]
The C directive is implemented using the L
module. A reference to the iterator object for a C directive is
implicitly available in the C variable. The following methods
can be called on the C 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 L for further details.
Example:
[% FOREACH item IN [ 'foo', 'bar', 'baz' ] -%]
[%- "\n" IF loop.first %]
- [% loop.count %]/[% loop.size %]: [% item %]
[%- "
\n" IF loop.last %]
[% END %]
Output:
- 1/3: foo
- 2/3: bar
- 3/3: baz
Nested loops will work as expected, with the C 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 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 C 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 C. See L 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 %]
=head2 WHILE
The C directive can be used to repeatedly process a template block
while a conditional expression evaluates true. The expression may
be arbitrarily complex as per C / C.
[% 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 C directive can be used to start the next iteration of a
C loop and C can be used to exit the loop, both as per C.
The Template Toolkit uses a failsafe counter to prevent runaway C
loops which would otherwise never terminate. If the loop exceeds 1000
iterations then an C exception will be thrown, reporting the
error:
WHILE loop terminated (> 1000 iterations)
The C<$Template::Directive::WHILE_MAX> variable controls this behaviour
and can be set to a higher value if necessary.
=head1 Filters, Plugins, Macros and Perl
=head2 FILTER
The C directive can be used to post-process the output of a
block. A number of standard filters are provided with the Template
Toolkit. The C filter, for example, escapes the 'E', 'E'
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 < and > characters embedded
which you want converted to the correct HTML entities.
The C directive can also follow various other non-block directives.
For example:
[% INCLUDE mytext FILTER html %]
The C<|> character can also be used as an alias for C.
[% 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 C filter is
an example of a static filter, implemented as:
sub html_filter {
my $text = shift;
for ($text) {
s/&/&/g;
s/</g;
s/>/>/g;
}
return $text;
}
Dynamic filters can accept arguments which are specified when the filter
is called from a template. The C 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 L object along
with any additional arguments specified. It should then return a
subroutine reference (e.g. a closure) which implements the filter.
The C 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 C option, described in L, allows custom
filters to be defined when a Template object is instantiated. The
L 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 C directive automatically quotes the name of the filter. As
with C et al, you can use a variable to provide the name of the
filter, prefixed by C<$>.
[% 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 C 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 C block
within a template that is loaded via C, 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
L method on the current
L object.
See L for a complete list of available filters,
their descriptions and examples of use.
=head2 USE
The C