config(3)

NAME

Template::Manual::Config - Configuration options

DESCRIPTION

This section contains details of all the configuration
options that can be used to customise the behaviour and
extend the features of the Template Toolkit.

Template Style and Parsing Options

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

[% example %]
Any Perl regex characters can be used and therefore
should be escaped (or use the Perl "quotemeta" func
tion) if they are intended to represent literal char
acters.

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

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

[% TAGS <+ +> %]
TAG_STYLE
The TAG_STYLE option can be used to set both START_TAG
and END_TAG according to pre-defined tag styles.

my $template = Template->new({
TAG_STYLE => 'star',
});
Available styles are:

template [% ... %] (default)
template1 [% ... %] or %% ... %% (TT version 1)
metatext %% ... %% (Text::Meta
Text)
star [* ... *] (TT alternate)
php <? ... ?> (PHP)
asp <% ... %> (ASP)
mason <% ... > (HTML::Mason)
html <!-- ... --> (HTML com
ments)
Any values specified for START_TAG and/or END_TAG will
over-ride those defined by a TAG_STYLE.
The TAGS directive may also be used to set a TAG_STYLE

[% TAGS html %]
<!-- INCLUDE header -->
PRE_CHOMP, POST_CHOMP
Anything outside a directive tag is considered plain
text and is generally passed through unaltered (but
see the INTERPOLATE option). This includes all
whitespace and newlines characters surrounding direc
tive tags. Directives that don't generate any output
will leave gaps in the output document.
Example:

Foo
[% a = 10 %]
Bar
Output:

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

my $template = Template->new({
PRE_CHOMP => 1,
POST_CHOMP => 1,
});
With PRE_CHOMP set to 1, the newline and whitespace
preceding a directive at the start of a line will be
deleted. This has the effect of concatenating a line
that starts with a directive onto the end of the pre
vious line.

Foo <----------.
,---(PRE_CHOMP)----'
`-- [% a = 10 %] --.
,---(POST_CHOMP)---'
`-> Bar
With POST_CHOMP set to 1, any whitespace after a
directive up to and including the newline will be
deleted. This has the effect of joining a line that
ends with a directive onto the start of the next line.
If PRE_CHOMP or POST_CHOMP is set to 2, then instead
of removing all the whitespace, the whitespace will be
collapsed to a single space. This is useful for HTML,
where (usually) a contiguous block of whitespace is
rendered the same as a single space.
You may use the CHOMP_NONE, CHOMP_ALL, and CHOMP_COL
LAPSE constants from the Template::Constants module to
deactivate chomping, remove all whitespace, or col
lapse whitespace to a single space.
PRE_CHOMP and POST_CHOMP can be activated for individ
ual directives by placing a '-' immediately at the
start and/or end of the directive.

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

[% FOREACH user = userlist %][% user %][% END %]
Note that this is the same as if PRE_CHOMP and
POST_CHOMP were set to CHOMP_ALL; the only way to get
the CHOMP_COLLAPSE behavior is to set PRE_CHOMP or
POST_CHOMP accordingly. If PRE_CHOMP or POST_CHOMP is
already set to CHOMP_COLLAPSE, using '-' will give you
CHOMP_COLLAPSE behavior, not CHOMP_ALL behavior.
Similarly, '+' characters can be used to disable
PRE_CHOMP or POST_CHOMP (i.e. leave the whites
pace/newline intact) options on a per-directive basis.

[% FOREACH user = userlist %]
User: [% user +%]
[% END %]
With POST_CHOMP enabled, the above example would be
parsed as if written:

[% FOREACH user = userlist %]User: [% user %]
[% END %]
TRIM
The TRIM option can be set to have any leading and
trailing whitespace automatically removed from the
output of all template files and BLOCKs.
By example, the following BLOCK definition

[% BLOCK foo %]
Line 1 of foo
[% END %]
will be processed is as "0ine 1 of foo0. When
INCLUDEd, the surrounding newlines will also be intro
duced.

before
[% INCLUDE foo %]
after
output:
before
Line 1 of foo
after
With the TRIM option set to any true value, the lead
ing and trailing newlines (which count as whitespace)
will be removed from the output of the BLOCK.

before
Line 1 of foo
after
The TRIM option is disabled (0) by default.
INTERPOLATE
The INTERPOLATE flag, when set to any true value will
cause variable references in plain text (i.e. not sur
rounded by START_TAG and END_TAG) to be recognised and
interpolated accordingly.

my $template = Template->new({
INTERPOLATE => 1,
});
Variables should be prefixed by a '$' to identify
them. Curly braces can be used in the familiar
Perl/shell style to explicitly scope the variable name
where required.

# INTERPOLATE => 0
<a href="http://[% server %]/[% help %]">
<img src="[% images %]/help.gif"></a>
[% myorg.name %]
# INTERPOLATE => 1
<a href="http://$server/$help">
<img src="$images/help.gif"></a>
$myorg.name
# explicit scoping with { }
<img src="$images/${icon.next}.gif">
Note that a limitation in Perl's regex engine
restricts the maximum length of an interpolated tem
plate to around 32 kilobytes or possibly less. Files
that exceed this limit in size will typically cause
Perl to dump core with a segmentation fault. If you
routinely process templates of this size then you
should disable INTERPOLATE or split the templates in
several smaller files or blocks which can then be
joined backed together via PROCESS or INCLUDE.
ANYCASE
By default, directive keywords should be expressed in
UPPER CASE. The ANYCASE option can be set to allow
directive keywords to be specified in any case.

# ANYCASE => 0 (default)
[% INCLUDE foobar %] # OK
[% include foobar %] # ERROR
[% include = 10 %] # OK, 'include' is a
variable
# ANYCASE => 1
[% INCLUDE foobar %] # OK
[% include foobar %] # OK
[% include = 10 %] # ERROR, 'include' is
reserved word
One side-effect of enabling ANYCASE is that you cannot
use a variable of the same name as a reserved word,
regardless of case. The reserved words are currently:

GET CALL SET DEFAULT INSERT INCLUDE PROCESS
WRAPPER
IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP
CLEAR TO STEP AND OR NOT MOD DIV END
The only lower case reserved words that cannot be used
for variables, regardless of the ANYCASE option, are
the operators:

and or not mod div
Template Files and Blocks
INCLUDE_PATH
The INCLUDE_PATH is used to specify one or more direc
tories in which template files are located. When a
template is requested that isn't defined locally as a
BLOCK, each of the INCLUDE_PATH directories is
searched in turn to locate the template file. Multi
ple directories can be specified as a reference to a
list or as a single string where each directory is
delimited by ':'.

my $template = Template->new({
INCLUDE_PATH => '/usr/local/templates',
});
my $template = Template->new({
INCLUDE_PATH => '/usr/local/tem
plates:/tmp/my/templates',
});
my $template = Template->new({
INCLUDE_PATH => [ '/usr/local/templates',
'/tmp/my/templates' ],
});
On Win32 systems, a little extra magic is invoked,
ignoring delimiters that have ':' followed by a '/' or
'´. This avoids confusion when using directory names
like 'C:0ah'.
When specified as a list, the INCLUDE_PATH path can
contain elements which dynamically generate a list of
INCLUDE_PATH directories. These generator elements
can be specified as a reference to a subroutine or an
object which implements a paths() method.

my $template = Template->new({
INCLUDE_PATH => [ '/usr/local/templates',
incpath_generator,
My::IncPath::Generator->new(
... ) ],
});
Each time a template is requested and the INCLUDE_PATH
examined, the subroutine or object method will be
called. A reference to a list of directories should
be returned. Generator subroutines should report
errors using die(). Generator objects should return
undef and make an error available via its error()
method.
For example:

sub incpath_generator {

# ...some code...
if ($all_is_well) {
return @list_of_directories;
}
else {
die "cannot generate INCLUDE_PATH...0;
}
}
or:

package My::IncPath::Generator;
# Template::Base (or Class::Base) provides error()
method
use Template::Base;
use base qw( Template::Base );
sub paths {
my $self = shift;
# ...some code...
if ($all_is_well) {
return @list_of_directories;
}
else {
return $self->error("cannot generate IN
CLUDE_PATH...0);
}
}
1;
DELIMITER
Used to provide an alternative delimiter character
sequence for separating paths specified in the
INCLUDE_PATH. The default value for DELIMITER is ':'.

# tolerate Silly Billy's file system conventions
my $template = Template->new({
DELIMITER => '; ',
INCLUDE_PATH => 'C:/HERE/NOW; D:/THERE/THEN',
});
# better solution: install Linux! :-)
On Win32 systems, the default delimiter is a little
more intelligent, splitting paths only on ':' charac
ters that aren't followed by a '/'. This means that
the following should work as planned, splitting the
INCLUDE_PATH into 2 separate directories, C:/foo and
C:/bar.

# on Win32 only
my $template = Template->new({
INCLUDE_PATH => 'C:/Foo:C:/Bar'
});
However, if you're using Win32 then it's recommended
that you explicitly set the DELIMITER character to
something else (e.g. ';') rather than rely on this
subtle magic.
ABSOLUTE
The ABSOLUTE flag is used to indicate if templates
specified with absolute filenames (e.g. '/foo/bar')
should be processed. It is disabled by default and
any attempt to load a template by such a name will
cause a 'file' exception to be raised.

my $template = Template->new({
ABSOLUTE => 1,
});
# this is why it's disabled by default
[% INSERT /etc/passwd %]
On Win32 systems, the regular expression for matching
absolute pathnames is tweaked slightly to also detect
filenames that start with a driver letter and colon,
such as:

C:/Foo/Bar
RELATIVE
The RELATIVE flag is used to indicate if templates
specified with filenames relative to the current
directory (e.g. './foo/bar' or
'../../some/where/else') should be loaded. It is also
disabled by default, and will raise a 'file' error if
such template names are encountered.

my $template = Template->new({
RELATIVE => 1,
});
[% INCLUDE ../logs/error.log %]
DEFAULT
The DEFAULT option can be used to specify a default
template which should be used whenever a specified
template can't be found in the INCLUDE_PATH.

my $template = Template->new({
DEFAULT => 'notfound.html',
});
If a non-existant template is requested through the
Template process() method, or by an INCLUDE, PROCESS or WRAPPER directive, then the DEFAULT template will
instead be processed, if defined. Note that the
DEFAULT template is not used when templates are speci
fied with absolute or relative filenames, or as a ref
erence to a input file handle or text string.
BLOCKS
The BLOCKS option can be used to pre-define a default
set of template blocks. These should be specified as
a reference to a hash array mapping template names to
template text, subroutines or Template::Document
objects.

my $template = Template->new({
BLOCKS => {
header => 'The Header. [% title %]',
footer => sub { return $some_output_text
},
another => Template::Document->new({ ...
}),
},
});
AUTO_RESET
The AUTO_RESET option is set by default and causes the
local BLOCKS cache for the Template::Context object to
be reset on each call to the Template process()
method. This ensures that any BLOCKs defined within a
template will only persist until that template is fin
ished processing. This prevents BLOCKs defined in one
processing request from interfering with other inde
pendent requests subsequently processed by the same
context object.
The BLOCKS item may be used to specify a default set
of block definitions for the Template::Context object.
Subsequent BLOCK definitions in templates will override these but they will be reinstated on each reset
if AUTO_RESET is enabled (default), or if the Tem
plate::Context reset() method is called.
RECURSION
The template processor will raise a file exception if
it detects direct or indirect recursion into a tem
plate. Setting this option to any true value will
allow templates to include each other recursively.
Template Variables
VARIABLES, PRE_DEFINE
The VARIABLES option (or PRE_DEFINE - they're equiva
lent) can be used to specify a hash array of template
variables that should be used to pre-initialise the
stash when it is created. These items are ignored if
the STASH item is defined.

my $template = Template->new({
VARIABLES => {
title => 'A Demo Page',
author => 'Joe Random Hacker',
version => 3.14,
},
};
or

my $template = Template->new({
PRE_DEFINE => {
title => 'A Demo Page',
author => 'Joe Random Hacker',
version => 3.14,
},
};
CONSTANTS
The CONSTANTS option can be used to specify a hash
array of template variables that are compile-time con
stants. These variables are resolved once when the
template is compiled, and thus don't require further
resolution at runtime. This results in significantly
faster processing of the compiled templates and can be
used for variables that don't change from one request
to the next.

my $template = Template->new({
CONSTANTS => {
title => 'A Demo Page',
author => 'Joe Random Hacker',
version => 3.14,
},
};
CONSTANT_NAMESPACE
Constant variables are accessed via the 'constants'
namespace by default.

[% constants.title %]
The CONSTANTS_NAMESPACE option can be set to specify
an alternate namespace.

my $template = Template->new({
CONSTANTS => {
title => 'A Demo Page',
# ...etc...
},
CONSTANTS_NAMESPACE => 'const',
};
In this case the constants would then be accessed as:

[% const.title %]
NAMESPACE
The constant folding mechanism described above is an
example of a namespace handler. Namespace handlers
can be defined to provide alternate parsing mechanisms
for variables in different namespaces.
Under the hood, the Template module converts a con
structor configuration such as:

my $template = Template->new({
CONSTANTS => {
title => 'A Demo Page',
# ...etc...
},
CONSTANTS_NAMESPACE => 'const',
};
into one like:

my $template = Template->new({
NAMESPACE => {
const => Template:::Namespace::Con
stants->new({
title => 'A Demo Page',
# ...etc...
}),
},
};
You can use this mechanism to define multiple constant
namespaces, or to install custom handlers of your own.

my $template = Template->new({
NAMESPACE => {
site => Template:::Namespace::Con
stants->new({
title => "Wardley's Widgets",
version => 2.718,
}),
author => Template:::Namespace::Con
stants->new({
name => 'Andy Wardley',
email => 'abw@andywardley.com',
}),
voodoo => My::Namespace::Handler->new( ...
),
},
};
Now you have 2 constant namespaces, for example:

[% site.title %]
[% author.name %]
as well as your own custom namespace handler installed
for the 'voodoo' namespace.

[% voodoo.magic %]
See Template::Namespace::Constants for an example of
what a namespace handler looks like on the inside.
Runtime Processing Options
EVAL_PERL
This flag is used to indicate if PERL and/or RAWPERL
blocks should be evaluated. By default, it is dis
abled and any PERL or RAWPERL blocks encountered will
raise exceptions of type 'perl' with the message
'EVAL_PERL not set'. Note however that any RAWPERL
blocks should always contain valid Perl code, regard
less of the EVAL_PERL flag. The parser will fail to
compile templates that contain invalid Perl code in
RAWPERL blocks and will throw a 'file' exception.
When using compiled templates (see COMPILE_EXT and
COMPILE_DIR), the EVAL_PERL has an affect when the
template is compiled, and again when the templates is
subsequently processed, possibly in a different con
text to the one that compiled it.
If the EVAL_PERL is set when a template is compiled,
then all PERL and RAWPERL blocks will be included in
the compiled template. If the EVAL_PERL option isn't
set, then Perl code will be generated which always
throws a 'perl' exception with the message 'EVAL_PERL
not set' whenever the compiled template code is run.
Thus, you must have EVAL_PERL set if you want your
compiled templates to include PERL and RAWPERL blocks.
At some point in the future, using a different invoca
tion of the Template Toolkit, you may come to process
such a pre-compiled template. Assuming the EVAL_PERL
option was set at the time the template was compiled,
then the output of any RAWPERL blocks will be included
in the compiled template and will get executed when
the template is processed. This will happen regard
less of the runtime EVAL_PERL status.
Regular PERL blocks are a little more cautious, how
ever. If the EVAL_PERL flag isn't set for the current context, that is, the one which is trying to process
it, then it will throw the familiar 'perl' exception
with the message, 'EVAL_PERL not set'.
Thus you can compile templates to include PERL blocks,
but optionally disable them when you process them
later. Note however that it is possible for a PERL
block to contain a Perl "BEGIN { # some code }" block
which will always get run regardless of the runtime
EVAL_PERL status. Thus, if you set EVAL_PERL when
compiling templates, it is assumed that you trust the
templates to Do The Right Thing. Otherwise you must
accept the fact that there's no bulletproof way to
prevent any included code from trampling around in the
living room of the runtime environment, making a real
nuisance of itself if it really wants to. If you
don't like the idea of such uninvited guests causing a
bother, then you can accept the default and keep
EVAL_PERL disabled.
PRE_PROCESS, POST_PROCESS
These values may be set to contain the name(s) of tem
plate files (relative to INCLUDE_PATH) which should be
processed immediately before and/or after each tem
plate. These do not get added to templates processed
into a document via directives such as INCLUDE, PRO
CESS, WRAPPER etc.

my $template = Template->new({
PRE_PROCESS => 'header',
POST_PROCESS => 'footer',
};
Multiple templates may be specified as a reference to
a list. Each is processed in the order defined.

my $template = Template->new({
PRE_PROCESS => [ 'config', 'header' ],
POST_PROCESS => 'footer',
};
Alternately, multiple template may be specified as a
single string, delimited by ':'. This delimiter
string can be changed via the DELIMITER option.

my $template = Template->new({
PRE_PROCESS => 'config:header',
POST_PROCESS => 'footer',
};
The PRE_PROCESS and POST_PROCESS templates are evalu
ated in the same variable context as the main document
and may define or update variables for subsequent use.
config:

[% # set some site-wide variables
bgcolor = '#ffffff'
version = 2.718
%]
header:

[% DEFAULT title = 'My Funky Web Site' %]
<html>
<head>
<title>[% title %]</title>
</head>
<body bgcolor="[% bgcolor %]">
footer:

<hr>
Version [% version %]
</body>
</html>
The Template::Document object representing the main
template being processed is available within PRE_PRO
CESS and POST_PROCESS templates as the 'template'
variable. Metadata items defined via the META direc
tive may be accessed accordingly.

$template->process('mydoc.html', $vars);
mydoc.html:

[% META title = 'My Document Title' %]
blah blah blah
...
header:

<html>
<head>
<title>[% template.title %]</title></head>
<body bgcolor="[% bgcolor %]">
PROCESS
The PROCESS option may be set to contain the name(s)
of template files (relative to INCLUDE_PATH) which
should be processed instead of the main template
passed to the Template process() method. This can be used to apply consistent wrappers around all tem
plates, similar to the use of PRE_PROCESS and
POST_PROCESS templates.

my $template = Template->new({
PROCESS => 'content',
};
# processes 'content' instead of 'foo.html'
$template->process('foo.html');
A reference to the original template is available in
the 'template' variable. Metadata items can be
inspected and the template can be processed by speci
fying it as a variable reference (i.e. prefixed by
'$') to an INCLUDE, PROCESS or WRAPPER directive.
content:

<html>
<head>
<title>[% template.title %]</title>
</head>
<body>
[% PROCESS $template %]
<hr>
&copy; Copyright [% template.copyright %]
</body>
</html>
foo.html:

[% META
title = 'The Foo Page'
author = 'Fred Foo'
copyright = '2000 Fred Foo'
%]
<h1>[% template.title %]</h1>
Welcome to the Foo Page, blah blah blah
output:

<html>
<head>
<title>The Foo Page</title>
</head>
<body>
<h1>The Foo Page</h1>
Welcome to the Foo Page, blah blah blah
<hr>
&copy; Copyright 2000 Fred Foo
</body>
</html>
ERROR
The ERROR (or ERRORS if you prefer) configuration item
can be used to name a single template or specify a
hash array mapping exception types to templates which
should be used for error handling. If an uncaught
exception is raised from within a template then the
appropriate error template will instead be processed.
If specified as a single value then that template will
be processed for all uncaught exceptions.

my $template = Template->new({
ERROR => 'error.html'
});
If the ERROR item is a hash reference the keys are
assumed to be exception types and the relevant tem
plate for a given exception will be selected. A
'default' template may be provided for the general
case. Note that 'ERROR' can be pluralised to 'ERRORS'
if you find it more appropriate in this case.

my $template = Template->new({
ERRORS => {
user => 'user/index.html',
dbi => 'error/database',
default => 'error/default',
},
});
In this example, any 'user' exceptions thrown will
cause the 'user/index.html' template to be processed,
'dbi' errors are handled by 'error/database' and all
others by the 'error/default' template. Any
PRE_PROCESS and/or POST_PROCESS templates will also be
applied to these error templates.
Note that exception types are hierarchical and a 'foo'
handler will catch all 'foo.*' errors (e.g. foo.bar,
foo.bar.baz) if a more specific handler isn't defined.
Be sure to quote any exception types that contain
periods to prevent Perl concatenating them into a sin
gle string (i.e. "user.passwd" is parsed as
'user'.'passwd').

my $template = Template->new({
ERROR => {
'user.login' => 'user/login.html',
'user.passwd' => 'user/badpasswd.html',
'user' => 'user/index.html',
'default' => 'error/default',
},
});
In this example, any template processed by the $tem
plate object, or other templates or code called from
within, can raise a 'user.login' exception and have
the service redirect to the 'user/login.html' tem
plate. Similarly, a 'user.passwd' exception has a
specific handling template, 'user/badpasswd.html',
while all other 'user' or 'user.*' exceptions cause a
redirection to the 'user/index.html' page. All other
exception types are handled by 'error/default'.
Exceptions can be raised in a template using the THROW
directive,

[% THROW user.login 'no user id: please login' %]
or by calling the throw() method on the current Tem
plate::Context object,

$context->throw('user.passwd', 'Incorrect Pass
word');
$context->throw('Incorrect Password'); # type
'undef'
or from Perl code by calling die() with a Tem
plate::Exception object,

die Template::Exception->new('user.denied', 'In
valid User ID');
or by simply calling die() with an error string. This
is automagically caught and converted to an exception
of 'undef' type which can then be handled in the usual
way.

die "I'm sorry Dave, I can't do that";
OUTPUT
Default output location or handler. This may be spec
ified as one of: a file name (relative to OUTPUT_PATH,
if defined, or the current working directory if not
specified absolutely); a file handle (e.g. GLOB or
IO::Handle) opened for writing; a reference to a text
string to which the output is appended (the string
isn't cleared); a reference to a subroutine which is
called, passing the output text as an argument; as a
reference to an array, onto which the content will be
push()ed; or as a reference to any object that sup
ports the print() method. This latter option includes the Apache::Request object which is passed as the
argument to Apache/mod_perl handlers.
example 1 (file name):

my $template = Template->new({
OUTPUT => "/tmp/foo",
});
example 2 (text string):

my $output = '';
my $template = Template->new({
OUTPUT => utput,
});
example 3 (file handle):

open (TOUT, "> $file") || die "$file: $!0;
my $template = Template->new({
OUTPUT => OUT,
});
example 4 (subroutine):

sub output { my $out = shift; print "OUTPUT: $out"
}
my $template = Template->new({
OUTPUT => output,
});
example 5 (array reference):

my $template = Template->new({
OUTPUT => @output,
})
example 6 (Apache/mod_perl handler):

sub handler {
my $r = shift;
my $t = Template->new({
OUTPUT => $r,
});
...
}
The default OUTPUT location be overridden by passing a
third parameter to the Template process() method. This can be specified as any of the above argument
types.

$t->process($file, $vars, "/tmp/foo");
$t->process($file, $vars, "bar");
$t->process($file, $vars, YGLOB);
$t->process($file, $vars, @output);
$t->process($file, $vars, $r); # Apache::Request
...
OUTPUT_PATH
The OUTPUT_PATH allows a directory to be specified
into which output files should be written. An output
file can be specified by the OUTPUT option, or passed
by name as the third parameter to the Template
process() method.

my $template = Template->new({
INCLUDE_PATH => "/tmp/src",
OUTPUT_PATH => "/tmp/dest",
});
my $vars = {
...
};
foreach my $file ('foo.html', 'bar.html') {
$template->process($file, $vars, $file)
|| die $template->error();
}
This example will read the input files
'/tmp/src/foo.html' and '/tmp/src/bar.html' and write
the processed output to '/tmp/dest/foo.html' and
'/tmp/dest/bar.html', respectively.
DEBUG
The DEBUG option enables debugging within the Template
Toolkit.

my $template = Template->new({
DEBUG => 1,
});
Setting this to a true value has two effects. The
first is that accessing any variable that returns an
undefined variable will cause an 'undef' error to be
raised.
The second is that the output generated by the Tem
plate Toolkit will have comments added indicating the
source file, line and original text of each directive
in the template.
For example, the following template fragment:

[% foo = 'World' %]
Hello [% foo %]
would generate this output:

## input text line 1 : [% foo = 'World' %] ##
Hello
## input text line 2 : [% foo %] ##
World
The DEBUG directive can be used to enable and disable
directive debugging at different parts of a template.
The DEBUG constructor option must be set for the DEBUG
directive to have any effect.

[% DEBUG on %]
[% foo = 'World' %]
[% DEBUG off %]
Hello [% foo %]
This template fragment would generate the following
output:

## input text line 1 : [% foo = 'World' %] ##
Hello World
It is anticipated that a future version of the Tem
plate Toolkit will support allow the different debug
ging options to be enabled or disabled individually.
DEBUG_FORMAT
The DEBUG_FORMAT option can be used to specify a for
mat string for the debugging messages described in the
DEBUG option above. Any occurances of $file, $line or
$text will be replaced with the current file name,
line or directive text, respectively. Notice how the
format is single quoted to prevent Perl from interpo
lating those tokens as variables.

my $template = Template->new({
DEBUG => 1,
DEBUG_FORMAT => '<!-- $file line $line : [%
$text %] -->',
});
The following template fragment:

[% DEBUG on %]
[% foo = 'World' %]
Hello [% foo %]
would then generate this output:

<!-- input text line 2 : [% foo = 'World' %] -->
Hello <!-- input text line 3 : [% foo %] -->World
The DEBUG directive can also be used to set a debug
format within a template.

[% DEBUG format '<!-- $file line $line : [% $text
%] -->' %]
Caching and Compiling Options
CACHE_SIZE
The Template::Provider module caches compiled tem
plates to avoid the need to re-parse template files or
blocks each time they are used. The CACHE_SIZE option
is used to limit the number of compiled templates that
the module should cache.
By default, the CACHE_SIZE is undefined and all com
piled templates are cached. When set to any positive
value, the cache will be limited to storing no more
than that number of compiled templates. When a new
template is loaded and compiled and the cache is full
(i.e. the number of entries == CACHE_SIZE), the least
recently used compiled template is discarded to make
room for the new one.
The CACHE_SIZE can be set to 0 to disable caching
altogether.

my $template = Template->new({
CACHE_SIZE => 64, # only cache 64 compiled
templates
});
my $template = Template->new({
CACHE_SIZE => 0, # don't cache any compiled
templates
});
COMPILE_EXT
From version 2 onwards, the Template Toolkit has the
ability to compile templates to Perl code and save
them to disk for subsequent use (i.e. cache persis
tence). The COMPILE_EXT option may be provided to
specify a filename extension for compiled template
files. It is undefined by default and no attempt will
be made to read or write any compiled template files.

my $template = Template->new({
COMPILE_EXT => '.ttc',
});
If COMPILE_EXT is defined (and COMPILE_DIR isn't, see
below) then compiled template files with the COM
PILE_EXT extension will be written to the same direc
tory from which the source template files were loaded.
Compiling and subsequent reuse of templates happens
automatically whenever the COMPILE_EXT or COMPILE_DIR
options are set. The Template Toolkit will automati
cally reload and reuse compiled files when it finds
them on disk. If the corresponding source file has
been modified since the compiled version as written,
then it will load and re-compile the source and write
a new compiled version to disk.
This form of cache persistence offers significant ben
efits in terms of time and resources required to
reload templates. Compiled templates can be reloaded
by a simple call to Perl's require(), leaving Perl to handle all the parsing and compilation. This is a
Good Thing.
COMPILE_DIR
The COMPILE_DIR option is used to specify an alternate
directory root under which compiled template files
should be saved.

my $template = Template->new({
COMPILE_DIR => '/tmp/ttc',
});
The COMPILE_EXT option may also be specified to have a
consistent file extension added to these files.

my $template1 = Template->new({
COMPILE_DIR => '/tmp/ttc',
COMPILE_EXT => '.ttc1',
});
my $template2 = Template->new({
COMPILE_DIR => '/tmp/ttc',
COMPILE_EXT => '.ttc2',
});
When COMPILE_EXT is undefined, the compiled template
files have the same name as the original template
files, but reside in a different directory tree.
Each directory in the INCLUDE_PATH is replicated in
full beneath the COMPILE_DIR directory. This example:

my $template = Template->new({
COMPILE_DIR => '/tmp/ttc',
INCLUDE_PATH => '/home/abw/tem
plates:/usr/share/templates',
});
would create the following directory structure:

/tmp/ttc/home/abw/templates/
/tmp/ttc/usr/share/templates/
Files loaded from different INCLUDE_PATH directories
will have their compiled forms save in the relevant
COMPILE_DIR directory.
On Win32 platforms a filename may by prefixed by a
drive letter and colon. e.g.

C:/My Templates/header
The colon will be silently stripped from the filename
when it is added to the COMPILE_DIR value(s) to pre
vent illegal filename being generated. Any colon in
COMPILE_DIR elements will be left intact. For exam
ple:

# Win32 only
my $template = Template->new({
DELIMITER => ';',
COMPILE_DIR => 'C:/TT2/Cache',
INCLUDE_PATH => 'C:/TT2/Templates;D:/My Tem
plates',
});
This would create the following cache directories:

C:/TT2/Cache/C/TT2/Templates
C:/TT2/Cache/D/My Templates
Plugins and Filters
PLUGINS
The PLUGINS options can be used to provide a reference
to a hash array that maps plugin names to Perl module
names. A number of standard plugins are defined (e.g.
'table', 'cgi', 'dbi', etc.) which map to their corre
sponding Template::Plugin::* counterparts. These can
be redefined by values in the PLUGINS hash.

my $template = Template->new({
PLUGINS => {
cgi => 'MyOrg::Template::Plugin::CGI',
foo => 'MyOrg::Template::Plugin::Foo',
bar => 'MyOrg::Template::Plugin::Bar',
},
});
The USE directive is used to create plugin objects and
does so by calling the plugin() method on the current Template::Context object. If the plugin name is
defined in the PLUGINS hash then the corresponding
Perl module is loaded via require(). The context then calls the load() class method which should return the
class name (default and general case) or a prototype
object against which the new() method can be called to
instantiate individual plugin objects.
If the plugin name is not defined in the PLUGINS hash
then the PLUGIN_BASE and/or LOAD_PERL options come
into effect.
PLUGIN_BASE
If a plugin is not defined in the PLUGINS hash then
the PLUGIN_BASE is used to attempt to construct a cor
rect Perl module name which can be successfully
loaded.
The PLUGIN_BASE can be specified as a single value or
as a reference to an array of multiple values. The
default PLUGIN_BASE value, 'Template::Plugin', is
always added the the end of the PLUGIN_BASE list (a
single value is first converted to a list). Each
value should contain a Perl package name to which the
requested plugin name is appended.
example 1:

my $template = Template->new({
PLUGIN_BASE => 'MyOrg::Template::Plugin',
});
[% USE Foo %] # => MyOrg::Template::Plugin::Foo
or Template::Plugin::Foo
example 2:

my $template = Template->new({
PLUGIN_BASE => [ 'MyOrg::Template::Plugin',
'YourOrg::Template::Plugin'
],
});
[% USE Foo %] # => MyOrg::Template::Plug
in::Foo
or YourOrg::Template::Plug
in::Foo
or Template::Plug
in::Foo
LOAD_PERL
If a plugin cannot be loaded using the PLUGINS or PLU
GIN_BASE approaches then the provider can make a final
attempt to load the module without prepending any pre
fix to the module path. This allows regular Perl mod
ules (i.e. those that don't reside in the Tem
plate::Plugin or some other such namespace) to be
loaded and used as plugins.
By default, the LOAD_PERL option is set to 0 and no
attempt will be made to load any Perl modules that
aren't named explicitly in the PLUGINS hash or reside
in a package as named by one of the PLUGIN_BASE compo
nents.
Plugins loaded using the PLUGINS or PLUGIN_BASE
receive a reference to the current context object as
the first argument to the new() constructor. Modules
loaded using LOAD_PERL are assumed to not conform to
the plugin interface. They must provide a new() class
method for instantiating objects but it will not
receive a reference to the context as the first argu
ment. Plugin modules should provide a load() class
method (or inherit the default one from the Tem
plate::Plugin base class) which is called the first
time the plugin is loaded. Regular Perl modules need
not. In all other respects, regular Perl objects and
Template Toolkit plugins are identical.
If a particular Perl module does not conform to the
common, but not unilateral, new() constructor conven
tion then a simple plugin wrapper can be written to
interface to it.
FILTERS
The FILTERS option can be used to specify custom fil
ters which can then be used with the FILTER directive
like any other. These are added to the standard fil
ters which are available by default. Filters speci
fied via this option will mask any standard filters of
the same name.
The FILTERS option should be specified as a reference
to a hash array in which each key represents the name
of a filter. The corresponding value should contain a
reference to an array containing a subroutine refer
ence and a flag which indicates if the filter is
static (0) or dynamic (1). A filter may also be spec
ified as a solitary subroutine reference and is
assumed to be static.

$template = Template->new({
FILTERS => {
'sfilt1' => static_filter, # static
'sfilt2' => [ static_filter, 0 ], # same
as above
'dfilt1' => [ dyanamic_filter_factory, 1
],
},
});
Additional filters can be specified at any time by
calling the define_filter() method on the current Tem plate::Context object. The method accepts a filter
name, a reference to a filter subroutine and an
optional flag to indicate if the filter is dynamic.

my $context = $template->context();
$context->define_filter('new_html', new_html);
$context->define_filter('new_repeat', new_repeat,
1);
Static filters are those where a single subroutine
reference is used for all invocations of a particular
filter. Filters that don't accept any configuration
parameters (e.g. 'html') can be implemented stati
cally. The subroutine reference is simply returned
when that particular filter is requested. The subrou
tine is called to filter the output of a template
block which is passed as the only argument. The sub
routine should return the modified text.

sub static_filter {
my $text = shift;
# do something to modify $text...
return $text;
}
The following template fragment:

[% FILTER sfilt1 %]
Blah blah blah.
[% END %]
is approximately equivalent to:

&static_filter("0lah blah blah.0);
Filters that can accept parameters (e.g. 'truncate')
should be implemented dynamically. In this case, the
subroutine is taken to be a filter 'factory' that is
called to create a unique filter subroutine each time
one is requested. A reference to the current Tem
plate::Context object is passed as the first parame
ter, followed by any additional parameters specified.
The subroutine should return another subroutine refer
ence (usually a closure) which implements the filter.

sub dynamic_filter_factory {
my ($context, @args) = @_;
return sub {
my $text = shift;
# do something to modify $text...
return $text;
}
}
The following template fragment:

[% FILTER dfilt1(123, 456) %]
Blah blah blah
[% END %]
is approximately equivalent to:

my $filter = &dynamic_filter_factory($context,
123, 456);
&$filter("0lah blah blah.0);
See the FILTER directive for further examples.
Compatibility, Customisation and Extension
V1DOLLAR
In version 1 of the Template Toolkit, an optional
leading '$' could be placed on any template variable
and would be silently ignored.

# VERSION 1
[% $foo %] === [% foo %]
[% $hash.$key %] === [% hash.key %]
To interpolate a variable value the '${' ... '}' con
struct was used. Typically, one would do this to
index into a hash array when the key value was stored
in a variable.
example:

my $vars = {
users => {
aba => { name => 'Alan Aardvark', ... },
abw => { name => 'Andy Wardley', ... },
...
},
uid => 'aba',
...
};
$template->process('user/home.html', $vars)
|| die $template->error(), "0;
'user/home.html':

[% user = users.${uid} %] # users.aba
Name: [% user.name %] # Alan Aardvark
This was inconsistent with double quoted strings and
also the INTERPOLATE mode, where a leading '$' in text
was enough to indicate a variable for interpolation,
and the additional curly braces were used to delimit
variable names where necessary. Note that this use is
consistent with UNIX and Perl conventions, among oth
ers.

# double quoted string interpolation
[% name = "$title ${user.name}" %]
# INTERPOLATE = 1
<img src="$images/help.gif"></a>
<img src="$images/${icon.next}.gif">
For version 2, these inconsistencies have been removed
and the syntax clarified. A leading '$' on a variable
is now used exclusively to indicate that the variable
name should be interpolated (e.g. subsituted for its
value) before being used. The earlier example from
version 1:

# VERSION 1
[% user = users.${uid} %]
Name: [% user.name %]
can now be simplified in version 2 as:

# VERSION 2
[% user = users.$uid %]
Name: [% user.name %]
The leading dollar is no longer ignored and has the
same effect of interpolation as '${' ... '}' in ver
sion 1. The curly braces may still be used to explic
itly scope the interpolated variable name where neces
sary.
e.g.

[% user = users.${me.id} %]
Name: [% user.name %]
The rule applies for all variables, both within direc
tives and in plain text if processed with the INTERPO
LATE option. This means that you should no longer (if
you ever did) add a leading '$' to a variable inside a
directive, unless you explicitly want it to be inter
polated.
One obvious side-effect is that any version 1 tem
plates with variables using a leading '$' will no
longer be processed as expected. Given the following
variable definitions,

[% foo = 'bar'
bar = 'baz'
%]
version 1 would interpret the following as:

# VERSION 1
[% $foo %] => [% GET foo %] => bar
whereas version 2 interprets it as:

# VERSION 2
[% $foo %] => [% GET $foo %] => [% GET bar %] =>
baz
In version 1, the '$' is ignored and the value for the
variable 'foo' is retrieved and printed. In version
2, the variable '$foo' is first interpolated to give
the variable name 'bar' whose value is then retrieved
and printed.
The use of the optional '$' has never been strongly
recommended, but to assist in backwards compatibility
with any version 1 templates that may rely on this
"feature", the V1DOLLAR option can be set to 1
(default: 0) to revert the behaviour and have leading
'$' characters ignored.

my $template = Template->new({
V1DOLLAR => 1,
});
LOAD_TEMPLATES
The LOAD_TEMPLATE option can be used to provide a ref
erence to a list of Template::Provider objects or subclasses thereof which will take responsibility for
loading and compiling templates.

my $template = Template->new({
LOAD_TEMPLATES => [
MyOrg::Template::Provider->new({ ... }),
Template::Provider->new({ ... }),
],
});
When a PROCESS, INCLUDE or WRAPPER directive is
encountered, the named template may refer to a locally
defined BLOCK or a file relative to the INCLUDE_PATH
(or an absolute or relative path if the appropriate
ABSOLUTE or RELATIVE options are set). If a BLOCK
definition can't be found (see the Template::Context
template() method for a discussion of BLOCK locality) then each of the LOAD_TEMPLATES provider objects is
queried in turn via the fetch() method to see if it
can supply the required template. Each provider can
return a compiled template, an error, or decline to
service the request in which case the responsibility
is passed to the next provider. If none of the
providers can service the request then a 'not found'
error is returned. The same basic provider mechanism
is also used for the INSERT directive but it bypasses
any BLOCK definitions and doesn't attempt is to parse
or process the contents of the template file.
This is an implementation of the 'Chain of Responsi
bility' design pattern as described in "Design Pat
terns", Erich Gamma, Richard Helm, Ralph Johnson, John
Vlissides), Addision-Wesley, ISBN 0-201-63361-2, page
223 .
If LOAD_TEMPLATES is undefined, a single default
provider will be instantiated using the current con
figuration parameters. For example, the Tem
plate::Provider INCLUDE_PATH option can be specified
in the Template configuration and will be correctly
passed to the provider's constructor method.

my $template = Template->new({
INCLUDE_PATH => '/here:/there',
});
LOAD_PLUGINS
The LOAD_PLUGINS options can be used to specify a list
of provider objects (i.e. they implement the fetch() method) which are responsible for loading and instan
tiating template plugin objects. The Template::Con
tent plugin() method queries each provider in turn in a "Chain of Responsibility" as per the template() and filter() methods.

my $template = Template->new({
LOAD_PLUGINS => [
MyOrg::Template::Plugins->new({ ... }),
Template::Plugins->new({ ... }),
],
});
By default, a single Template::Plugins object is cre
ated using the current configuration hash. Configura
tion items destined for the Template::Plugins con
structor may be added to the Template constructor.

my $template = Template->new({
PLUGIN_BASE => 'MyOrg::Template::Plugins',
LOAD_PERL => 1,
});
LOAD_FILTERS
The LOAD_FILTERS option can be used to specify a list
of provider objects (i.e. they implement the fetch() method) which are responsible for returning and/or
creating filter subroutines. The Template::Context
filter() method queries each provider in turn in a "Chain of Responsibility" as per the template() and plugin() methods.

my $template = Template->new({
LOAD_FILTERS => [
MyTemplate::Filters->new(),
Template::Filters->new(),
],
});
By default, a single Template::Filters object is cre
ated for the LOAD_FILTERS list.
TOLERANT
The TOLERANT flag is used by the various Template
Toolkit provider modules (Template::Provider, Tem
plate::Plugins, Template::Filters) to control their
behaviour when errors are encountered. By default,
any errors are reported as such, with the request for
the particular resource (template, plugin, filter)
being denied and an exception raised. When the TOLER
ANT flag is set to any true values, errors will be
silently ignored and the provider will instead return
STATUS_DECLINED. This allows a subsequent provider to
take responsibility for providing the resource, rather
than failing the request outright. If all providers
decline to service the request, either through toler
ated failure or a genuine disinclination to comply,
then a '<resource> not found' exception is raised.
SERVICE
A reference to a Template::Service object, or subclass thereof, to which the Template module should
delegate. If unspecified, a Template::Service object
is automatically created using the current configura
tion hash.

my $template = Template->new({
SERVICE => MyOrg::Template::Service->new({ ...
}),
});
CONTEXT
A reference to a Template::Context object which is
used to define a specific environment in which tem
plate are processed. A Template::Context object is
passed as the only parameter to the Perl subroutines
that represent "compiled" template documents. Tem
plate subroutines make callbacks into the context
object to access Template Toolkit functionality, for
example, to to INCLUDE or PROCESS another template
(include() and process() methods, respectively), to USE a plugin (plugin()) or instantiate a filter (fil_ ter()) or to access the stash (stash()) which manages variable definitions via the get() and set() methods.

my $template = Template->new({
CONTEXT => MyOrg::Template::Context->new({ ...
}),
});
STASH
A reference to a Template::Stash object or sub-class
which will take responsibility for managing template
variables.

my $stash = MyOrg::Template::Stash->new({ ... });
my $template = Template->new({
STASH => $stash,
});
If unspecified, a default stash object is created
using the VARIABLES configuration item to initialise
the stash variables. These may also be specified as
the PRE_DEFINE option for backwards compatibility with
version 1.

my $template = Template->new({
VARIABLES => {
id => 'abw',
name => 'Andy Wardley',
},
};
PARSER
The Template::Parser module implements a parser object
for compiling templates into Perl code which can then
be executed. A default object of this class is cre
ated automatically and then used by the Tem
plate::Provider whenever a template is loaded and
requires compilation. The PARSER option can be used
to provide a reference to an alternate parser object.

my $template = Template->new({
PARSER => MyOrg::Template::Parser->new({ ...
}),
});
GRAMMAR
The GRAMMAR configuration item can be used to specify
an alternate grammar for the parser. This allows a
modified or entirely new template language to be con
structed and used by the Template Toolkit.
Source templates are compiled to Perl code by the Tem
plate::Parser using the Template::Grammar (by default)
to define the language structure and semantics. Com
piled templates are thus inherently "compatible" with
each other and there is nothing to prevent any number
of different template languages being compiled and
used within the same Template Toolkit processing envi
ronment (other than the usual time and memory con
straints).
The Template::Grammar file is constructed from a YACC
like grammar (using Parse::YAPP) and a skeleton module
template. These files are provided, along with a
small script to rebuild the grammar, in the 'parser'
sub-directory of the distribution. You don't have to
know or worry about these unless you want to hack on
the template language or define your own variant.
There is a README file in the same directory which
provides some small guidance but it is assumed that
you know what you're doing if you venture herein. If
you grok LALR parsers, then you should find it com
fortably familiar.
By default, an instance of the default Template::Gram
mar will be created and used automatically if a GRAM
MAR item isn't specified.

use MyOrg::Template::Grammar;
my $template = Template->new({
GRAMMAR = MyOrg::Template::Grammar->new();
});

AUTHOR

Andy Wardley <abw@andywardley.com>

<http://www.andywardley.com/|http://www.andywardley.com/>

VERSION

Template Toolkit version 2.08, released on 30 July 2002.

COPYRIGHT

Copyright (C) 1996-2002 Andy Wardley. All Rights Re
served.
Copyright (C) 1998-2002 Canon Research Centre Europe
Ltd.
This module is free software; you can redistribute it
and/or modify it under the same terms as Perl itself.
Copyright © 2010-2025 Platon Technologies, s.r.o.           Home | Man pages | tLDP | Documents | Utilities | About
Design by styleshout