Template::Manual::Directives(3)User Contributed Perl DocumentationTemplate::Manual::Directives(3)
NAME
Template::Manual::Directives - Template directives
Accessing and Updating Template Variables
GET
The "GET" directive retrieves and outputs the value of the named variable.
[% GET foo %]
The "GET" keyword is optional. A variable can be specified in a directive tag by itself.
[% foo %]
The variable can have an unlimited number of elements, each separated by a dot. Each ele-
ment 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 (i.e. remainder) of division.
[% 15 / 6 %] # 2.5
[% 15 div 6 %] # 2
[% 15 mod 6 %] # 3
CALL
The "CALL" directive is similar to "GET" in evaluating the variable named, but doesn't
print the result returned. This can be useful when a variable is bound to a sub-routine
or object method which you want to call but aren't interested in the value returned.
[% CALL dbi.disconnect %]
[% CALL inc_page_counter(page_count) %]
SET
The "SET" directive allows you to assign new values to existing variables or create new
temporary variables.
[% SET title = 'Hello World' %]
The "SET" keyword is also optional.
[% title = 'Hello World' %]
Variables may be assigned the values of other variables, unquoted numbers (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. Thus, the above could have been written:
[% foo = 'Foo'
bar = foo
cost = '$100'
item = "$bar: ${cost}.00"
%]
Simple expressions can also be used, as per "GET".
[% ten = 10
twenty = 20
thirty = twenty + ten
forty = 2 * twenty
fifty = 100 div 2
six = twenty mod 7
%]
You can concatenate strings together using the ' _ ' operator. In Perl 5, the "." is used
for string concatenation, but in Perl 6, as in the Template Toolkit, the "." will be used
as the method calling operator and ' _ ' will be used for string concatenation. Note that
the operator must be specified with surrounding whitespace which, as Larry says, is con-
strued 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" %]
DEFAULT
The "DEFAULT" directive is similar to "SET" but only updates variables that are currently
undefined or have no "true" value (in the Perl sense).
[% DEFAULT
name = 'John Doe'
id = 'jdoe'
%]
This can be particularly useful in common template components to ensure that some sensible
default are provided for otherwise undefined variables.
[% DEFAULT
title = 'Hello World'
bgcol = '#ffffff'
%]
[% title %]
...etc...
Processing Template Files and Blocks
INSERT
The "INSERT" directive is used to insert the contents of an external file at the current
position.
[% INSERT myfile %]
No attempt to parse or process the file is made. The contents, possibly including any
embedded template directives, are inserted intact.
The filename specified should be relative to one of the "INCLUDE_PATH" directories. Abso-
lute (i.e. starting with "/") and relative (i.e. starting with ".") filenames may be used
if the "ABSOLUTE" and "RELATIVE" options are set, respectively. Both these options are
disabled by default.
my $template = Template->new({
INCLUDE_PATH => '/here:/there',
});
$template->process('myfile');
myfile:
[% INSERT foo %] # looks for /here/foo then /there/foo
[% INSERT /etc/passwd %] # file error: ABSOLUTE not set
[% INSERT ../secret %] # file error: RELATIVE not set
For convenience, the filename does not need to be quoted as long as it contains only
alphanumeric characters, underscores, dots or forward slashes. Names containing any other
characters should be quoted.
[% INSERT misc/legalese.txt %]
[% INSERT 'dos98/Program Files/stupid' %]
To evaluate a variable to specify a filename, you should explicitly prefix it with a "$"
or use double-quoted string interpolation.
[% language = 'en'
legalese = 'misc/legalese.txt'
%]
[% INSERT $legalese %] # misc/legalese.txt
[% INSERT "$language/$legalese" %] # en/misc/legalese.txt
Multiple files can be specified using "+" 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
INCLUDE
The "INCLUDE" directive is used to process and include the output of another template file
or block.
[% INCLUDE header %]
If a "BLOCK" of the specified name is defined in the same file, or in a file from which
the current template has been called (i.e. a parent template) then it will be used in
preference to any file of the same name.
[% INCLUDE table %] # uses BLOCK defined below
[% BLOCK table %]
[% END %]
If a "BLOCK" definition is not currently visible then the template name should be a file
relative to one of the "INCLUDE_PATH" directories, or an absolute or relative file name if
the "ABSOLUTE"/"RELATIVE" options are appropriately enabled. The "INCLUDE" directive
automatically quotes the filename specified, as per "INSERT" described above. When a
variable contains the name of the template for the "INCLUDE" directive, it should be
explicitly prefixed by "$" 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 vari-
ables currently defined will be visible and accessible from within the included template.
[% title = 'Hello World' %]
[% INCLUDE header %]
...
header:
[% 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 "INCLUDE" directive localises (i.e. copies) all variables before processing the tem-
plate. Any changes made within the included template will not affect variables in the
including template.
[% foo = 10 %]
foo is originally [% foo %]
[% INCLUDE bar %]
foo is still [% foo %]
[% BLOCK bar %]
foo was [% foo %]
[% foo = 20 %]
foo is now [% foo %]
[% END %]
output:
foo is originally 10
foo was 10
foo is now 20
foo is still 10
Technical Note: the localisation of the stash (that is, the process by which variables are
copied before an "INCLUDE" to prevent being overwritten) is only skin deep. The top-level
variable namespace (hash) is copied, but no attempt is made to perform a deep-copy of
other structures (hashes, arrays, objects, etc.) Therefore, a "foo" variable referencing
a hash will be copied to create a new "foo" variable but which points to the same hash
array. Thus, if you update compound variables (e.g. "foo.bar") then you will change the
original copy, regardless of any stash localisation. If you're not worried about preserv-
ing variable values, or you trust the templates you're including then you might prefer to
use the "PROCESS" directive which is faster by virtue of not performing any localisation.
You can specify dotted variables as "local" variables to an "INCLUDE" directive. However,
be aware that because of the localisation issues explained above (if you skipped the pre-
vious Technical Note above then you might want to go back and read it or skip this section
too), the variables might not actualy be "local". If the first element of the variable
name already references a hash array then the variable update will affect the original
variable.
[% 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 "INCLUDE"
and other similar directives.
If you want to process several templates in one go then you can specify each of their
names (quoted or unquoted names only, no unquoted $variables) joined together by "+". The
"INCLUDE" directive will then process them in order.
[% 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 specify-
ing several separate "INCLUDE" directives (because you only clone the variable stash once
instead of n times), but not quite as "safe" because any variable changes in the first
file will be visible in the second, third and so on. This might be what you want, of
course, but then again, it might not.
PROCESS
The PROCESS directive is similar to "INCLUDE" but does not perform any localisation of
variables before processing the template. Any changes made to variables within the
included template will be visible in the including template.
[% foo = 10 %]
foo is [% foo %]
[% PROCESS bar %]
foo is [% foo %]
[% BLOCK bar %]
[% foo = 20 %]
changed foo to [% foo %]
[% END %]
output:
foo is 10
changed foo to 20
foo is 20
Parameters may be specified in the "PROCESS" directive, but these too will become visible
changes to current variable values.
[% foo = 10 %]
foo is [% foo %]
[% PROCESS bar
foo = 20
%]
foo is [% foo %]
[% BLOCK bar %]
this is bar, foo is [% foo %]
[% END %]
output:
foo is 10
this is bar, foo is 20
foo is 20
The "PROCESS" directive is slightly faster than "INCLUDE" because it avoids the need to
localise (i.e. copy) the variable stash before processing the template. As with "INSERT"
and "INCLUDE", the first parameter does not need to be quoted as long as it contains only
alphanumeric characters, underscores, periods or forward slashes. A "$" prefix can be
used to explicitly indicate a variable which should be interpolated to provide the tem-
plate name:
[% myheader = 'my/misc/header' %]
[% PROCESS myheader %] # 'myheader'
[% PROCESS $myheader %] # 'my/misc/header'
As with "INCLUDE", multiple templates can be specified, delimited by "+", and are pro-
cessed in order.
[% PROCESS html/header + my/header %]
WRAPPER
It's not unusual to find yourself adding common headers and footers to pages or sub-sec-
tions 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 "WRAPPER" directive provides a way of simplifying this a little. It encloses a block
up to a matching "END" directive, which is first processed to generate some output. This
is then passed to the named template file or "BLOCK" as the "content" variable.
[% WRAPPER section
title = 'Quantum Mechanics'
%]
Quantum mechanics is a very interesting subject wish
should prove easy for the layman to fully comprehend.
[% END %]
[% WRAPPER section
title = 'Desktop Nuclear Fusion for under $50'
%]
This describes a simple device which generates significant
sustainable electrical power from common tap water by process
of nuclear fusion.
[% END %]
The single 'section' template can then be defined as:
[% 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 "WRAPPER" directive. The specifica-
tion 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
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 %]
|