Templat...:Config(3)
π NAME π
Template::Manual::Config β the configuration options manual page, aka the big book of "how do I make my templates behave", and yes bestie we're reading the whole thing π
β¨ Template Style and Parsing Options β¨
π ENCODING π
The ENCODING option tells the template files what character encoding they're speaking:
my $template = Template->new({
ENCODING => 'utf8',
});
And lowkey iconic behaviour: if a template starts with a Unicode byte order mark (BOM), its encoding gets detected automatically. No cap, it just knows π«
π¦ START_TAG, END_TAG π¦
START_TAG and END_TAG are the options that say which character sequences (or regular expressions) mark the start and end of inline template directives. Out of the box, START_TAG is '[%' and END_TAG is '%]', which is why we all know and love the classic look:
[% example %]
Any Perl regex characters are fair game here, so if you actually mean them as literal characters, escape them (or just use Perl's quotemeta function, she's right there):
my $template = Template->new({
START_TAG => quotemeta('<+'),
END_TAG => quotemeta('+>'),
});
Example:
<+ INCLUDE foobar +>
You can also set START_TAG and END_TAG per template file with the TAGS directive. Slay, per-file control π«Ά
[% TAGS <+ +> %]
πΈ OUTLINE_TAG πΈ
OUTLINE_TAG turns on single-line "outline" directives. So convenient.
my $template = Template->new({
OUTLINE_TAG => '%%',
});
Which lets you mix and match inline and outline tags like this:
%% IF user
Hello [% user.name %]
%% END
Rules of the game: the OUTLINE_TAG string (or regex) must appear at the start of a line. The directive continues until the end of the line, and the newline character at the end of that line is treated as the invisible end-of-directive marker β and it gets removed. Sneaky but polite π§
β TAG_STYLE β
TAG_STYLE sets both START_TAG and END_TAG at once from a pre-defined tag style. One option, both tags, main character energy π
my $template = Template->new({
TAG_STYLE => 'star',
});
The available styles are:
templateβ[% ... %](default)template1β[% ... %]or%% ... %%(TT version 1)metatextβ%% ... %%(Text::MetaText)starβ[* ... *](TT alternate)phpβ<? ... ?>(PHP)aspβ<% ... %>(ASP)masonβ<% ... >(HTML::Mason)htmlβ<!-- ... -->(HTML comments)
The outline style uses the default markers for START_TAG and END_TAG ([% and %] respectively) and additionally defines OUTLINE_TAG to be %%.
my $template = Template->new({
TAG_STYLE => 'outline',
});
So you get both inline and outline tags at the same time, like so:
%% IF user
Hello [% user.name %]
%% END
Heads up: any values you specify for START_TAG, END_TAG and/or OUTLINE_TAG will override whatever a TAG_STYLE defined. You win, always π
Also the TAGS directive can set a TAG_STYLE:
[% TAGS html %]
<!-- INCLUDE header -->
π PRE_CHOMP, POST_CHOMP π
Okay so literally anything outside a directive tag counts as plain text and generally passes through unaltered (but see the INTERPOLATE option, keep reading bestie). That includes all the whitespace and newline characters hanging around directive tags. And directives that don't generate any output? They just leave gaps in the output document. Gaps! Rude.
Example:
Foo
[% a = 10 %]
Bar
Output:
Foo
Bar
PRE_CHOMP and POST_CHOMP are the options that help clean up some of this extraneous whitespace. Both are disabled 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 get deleted. The effect? A line that starts with a directive gets concatenated onto the end of the previous line. Look at this little diagram, she's so helpful:
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 gets deleted, which joins a line that ends with a directive onto the start of the next line.
If PRE_CHOMP or POST_CHOMP is set to 2, all whitespace including any number of newlines gets removed and replaced with a single space. Super useful for HTML, where (usually) a contiguous block of whitespace renders exactly the same as a single space. Rendering said: same vibe, fewer characters π
With PRE_CHOMP or POST_CHOMP set to 3, all adjacent whitespace (including newlines) gets removed entirely. Gone. Poof. π¨
These values are defined as the CHOMP_NONE, CHOMP_ONE, CHOMP_COLLAPSE and CHOMP_GREEDY constants in the Template::Constants module. And CHOMP_ALL is also defined as an alias for CHOMP_ONE, purely for backwards compatibility with earlier versions of the Template Toolkit. Nostalgia core.
Oh and additionally, the chomp tag modifiers listed below can also be used for the PRE_CHOMP and POST_CHOMP configuration:
my $template = Template->new({
PRE_CHOMP => '~',
POST_CHOMP => '-',
});
You can also activate PRE_CHOMP and POST_CHOMP for individual directives by placing a '-' immediately at the start and/or end of the directive:
[% FOREACH user IN userlist %]
[%- user -%]
[% END %]
This does the same thing as CHOMP_ONE β removing all whitespace before or after the directive, up to and including the newline. The template gets processed as if you'd written:
[% FOREACH user IN userlist %][% user %][% END %]
To remove all whitespace including any number of newlines, use the '~' tilde character instead:
[% FOREACH user IN userlist %]
[%~ user ~%]
[% END %]
To collapse all whitespace down to a single space, use the '=' equals sign character:
[% FOREACH user IN userlist %]
[%= user =%]
[% END %]
Here the template is processed as if written:
[% FOREACH user IN userlist %] [% user %] [% END %]
And if you've got PRE_CHOMP or POST_CHOMP set as configuration options, you can use the '+' plus sign to disable any chomping options (i.e. leave the whitespace exactly as it is, untouched, respected) on a per-directive basis:
[% FOREACH user IN userlist %]
User: [% user +%]
[% END %]
With POST_CHOMP set to CHOMP_ONE, the above example would be parsed as if written:
[% FOREACH user IN userlist %]User: [% user %]
[% END %]
For reference (and because we love a cheat sheet), the PRE_CHOMP and POST_CHOMP configuration options may be set to any of the following:
Constant Value Tag Modifier
----------------------------------
CHOMP_NONE 0 +
CHOMP_ONE 1 -
CHOMP_COLLAPSE 2 =
CHOMP_GREEDY 3 ~
π TRIM π
TRIM can be set so that any leading and trailing whitespace gets automatically removed from the output of all template files and BLOCKs. Fresh, clean, exfoliated output β¨
By example, this BLOCK definition:
[% BLOCK foo %]
Line 1 of foo
[% END %]
will be processed is as "\nLine 1 of foo\n". And when it's INCLUDEd, the surrounding newlines get introduced too:
before
[% INCLUDE foo %]
after
Generated output:
before
Line 1 of foo
after
With the TRIM option set to any true value, the leading and trailing newlines (which count as whitespace, in case you were wondering) get removed from the output of the BLOCK:
before
Line 1 of foo
after
TRIM is disabled (0) by default.
π INTERPOLATE π
The INTERPOLATE flag, when set to any true value, makes variable references in plain text (i.e. not surrounded by START_TAG and END_TAG) get recognised and interpolated accordingly. Yes, in the actual text. Iconic.
my $template = Template->new({
INTERPOLATE => 1,
});
Variables should be prefixed by a '$' dollar sign so we know who they are. And curly braces '{' and '}' can be used in the familiar Perl/shell style to explicitly scope the variable name whenever you need to be precise about it:
# 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">
β οΈ Real talk, this one matters: a limitation in Perl's regex engine restricts the maximum length of an interpolated template 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 disableINTERPOLATE, or split the templates into several smaller files or blocks which can then be joined back together viaPROCESSorINCLUDE. Do not ignore this, bestie, fr fr.
π¦ ANYCASE π¦
By default, directive keywords should be expressed in UPPER CASE (screaming, as nature intended). The ANYCASE option can be set to allow directive keywords in any case at all.
# 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: you cannot use a variable with the same name as a reserved word, regardless of case. Them's the rules. 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 can't be used for variables, regardless of the ANYCASE option, are the operators:
and or not mod div
π Template Files and Blocks π
Okay so this is the part where we talk about where templates actually live, how they get found, and all the little knobs that control the vibe. Main character energy only. π¦
β¨ INCLUDE_PATH β¨
The INCLUDE_PATH is used to specify one or more directories 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. Multiple directories can be specified as a reference to a list or as a single string where each directory is delimited by the ":" colon character.
my $template = Template->new({
INCLUDE_PATH => '/usr/local/templates',
});
my $template = Template->new({
INCLUDE_PATH => '/usr/local/templates:/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 ":" colon followed by a "/" slash or "\" backslash. This avoids confusion when using directory names like "C:\Blah Blah". πͺ
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...\n";
}
}
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 INCLUDE_PATH...\n");
}
}
1;
π DELIMITER π
Used to provide an alternative delimiter character sequence for separating paths specified in the INCLUDE_PATH. The default value for DELIMITER is the ":" colon character.
my $template = Template->new({
DELIMITER => '; ',
INCLUDE_PATH => 'C:/HERE/NOW; D:/THERE/THEN',
});
On Win32 systems, the default delimiter is a little more intelligent, splitting paths only on ":" colon characters that aren't followed by a "/" slash character. 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. ";" semicolon) 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-existent 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 specified with absolute or relative filenames, or as a reference 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({ ... }),
},
});
π VIEWS π
The VIEWS option can be used to define one or more Template::View objects. They can be specified as a reference to a hash array or list reference.
my $template = Template->new({
VIEWS => {
my_view => { prefix => 'my_templates/' },
},
});
Be aware of the fact that Perl's hash array are unordered, so if you want to specify multiple views of which one or more are based on other views, then you should use a list reference to preserve the order of definition.
my $template = Template->new({
VIEWS => [
bottom => { prefix => 'bottom/' },
middle => { prefix => 'middle/', base => 'bottom' },
top => { prefix => 'top/', base => 'middle' },
],
});
π₯ 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 finished processing. This prevents BLOCKs defined in one processing request from interfering with other independent 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 over-ride these but they will be reinstated on each reset if AUTO_RESET is enabled (default), or if the Template::Context reset() method is called.
β RECURSION β
The template processor will raise a file exception if it detects direct or indirect recursion into a template. Setting this option to any true value will allow templates to include each other recursively. π
πΈ Template Variables πΈ
Okay bestie, now we're getting into the variables zone, and this is where you get to pre-load your stash with all the good stuff before the template even wakes up. π
VARIABLES
So the VARIABLES option (or PRE_DEFINE β they're literally the same thing, pick whichever one your heart says) lets you hand over a hash array of template variables that get used to pre-initialise the stash when it's created. π
Heads up: these items are ignored if the STASH item is defined. Like, completely ignored. So don't set both and then act confused, iykyk.
my $template = Template->new({
VARIABLES => {
title => 'A Demo Page',
author => 'Joe Random Hacker',
version => 3.14,
},
});
or, same energy, different spelling:
my $template = Template->new({
PRE_DEFINE => {
title => 'A Demo Page',
author => 'Joe Random Hacker',
version => 3.14,
},
});
CONSTANTS
CONSTANTS is the β¨ icon β¨ option β you give it a hash array of template variables that are compile-time constants. They get resolved once, at the moment the template is compiled, so they don't need to be resolved again at runtime. The way that this makes compiled templates run significantly faster?? Chefs kiss. π
Perfect for stuff that doesn'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
By default, constant variables are accessed through the constants namespace:
[% constants.title %]
But plot twist β you can set the CONSTANTS_NAMESPACE option to specify an alternate namespace. π
my $template = Template->new({
CONSTANTS => {
title => 'A Demo Page',
# ...etc...
},
CONSTANTS_NAMESPACE => 'const',
});
And then in this case the constants would be accessed like this:
[% const.title %]
NAMESPACE
That constant folding mechanism from just now? It's actually an example of a namespace handler. Namespace handlers can be defined to provide alternate parsing mechanisms for variables living in different namespaces. Lowkey genius. π§
Under the hood, the Template module takes a constructor configuration like this:
my $template = Template->new({
CONSTANTS => {
title => 'A Demo Page',
# ...etc...
},
CONSTANTS_NAMESPACE => 'const',
});
and converts it into one like this:
my $template = Template->new({
NAMESPACE => {
const => Template:::Namespace::Constants->new({
title => 'A Demo Page',
# ...etc...
}),
},
});
So you can use this whole mechanism to define multiple constant namespaces, or to install custom handlers of your very own. Main character energy fr fr. π
my $template = Template->new({
NAMESPACE => {
site => Template:::Namespace::Constants->new({
title => "Wardley's Widgets",
version => 2.718,
}),
author => Template:::Namespace::Constants->new({
name => 'Andy Wardley',
email => 'abw@andywardley.com',
}),
voodoo => My::Namespace::Handler->new( ... ),
},
});
Now you've got two constant namespaces, like:
[% site.title %]
[% author.name %]
plus your own custom namespace handler installed for the voodoo namespace:
[% voodoo.magic %]
Wanna see what a namespace handler looks like from the inside? Go peek at Template::Namespace::Constants β it's right there. π
π₯ Template Processing Options π₯
These next options are all about specifying additional templates that should be processed before, after, around, or instead of the template you passed as the first argument to the Template process() method. Super useful for adding standard headers or footers to every page, wrapping page output in other templates, pre-defining variables, doing initialisation or cleanup tasks, auto-generating page summary info, navigation elements, and so on. Basically the whole glue-things-together toolkit. π
The task of processing the template gets delegated internally to the Template::Service module which β unsurprisingly β also has a process() method.
Here's the order of operations, bestie, write it down: π
- Any templates defined by the
PRE_PROCESSoption are processed first, and any output generated gets added to the output buffer. - Then the main template is processed β or, if one or more
PROCESStemplates are defined, those get processed in turn instead. In that case, one of thePROCESStemplates is responsible for processing the main template, via a directive like:
[% PROCESS $template %]
- The output of processing the main template or the
PROCESStemplate(s) is then wrapped in anyWRAPPERtemplates, if defined.WRAPPERtemplates don't need to worry about explicitly processing the template β it's already been done for them. Instead,WRAPPERtemplates access the content they're wrapping through thecontentvariable. π¦
wrapper before
[% content %]
wrapper after
- This output β generated from processing the main template and/or any
PROCESSorWRAPPERtemplates β gets added to the output buffer. - Finally, any
POST_PROCESStemplates are processed, their output is also added to the output buffer, and then the whole buffer is returned. Slay. β¨
Now for the plot twist nobody asked for π: if the main template throws an exception during processing, then any relevant template(s) defined via the ERROR option get processed instead. If such a template is defined and processes successfully, its output is added to the output buffer in place of the template that generated the error, and processing continues β applying any WRAPPER and POST_PROCESS templates along the way.
But if no relevant ERROR option is defined, or if the error happens in one of the PRE_PROCESS, WRAPPER or POST_PROCESS templates, then the process terminates immediately and the error gets returned. No recovery, no vibes, just the error. π
PRE_PROCESS, POST_PROCESS
These values can contain the name(s) of template files (relative to INCLUDE_PATH) that should be processed immediately before and/or after each template. Important detail: these do not get added to templates processed into a document via directives such as INCLUDE, PROCESS, WRAPPER etc. They're for the main event only. π
my $template = Template->new({
PRE_PROCESS => 'header',
POST_PROCESS => 'footer',
});
You can specify multiple templates by passing a reference to a list. Each one gets processed in the order defined.
my $template = Template->new({
PRE_PROCESS => [ 'config', 'header' ],
POST_PROCESS => 'footer',
});
Alternately, multiple templates can be specified as a single string, delimited by ':'. And yes, you can change that delimiter string via the DELIMITER option. π
my $template = Template->new({
PRE_PROCESS => 'config:header',
POST_PROCESS => 'footer',
});
The PRE_PROCESS and POST_PROCESS templates are evaluated in the same variable context as the main document, and they may define or update variables for subsequent use. So yes, they can leave little gifts for the templates that come after them. π
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 inside PRE_PROCESS and POST_PROCESS templates as the template variable. Which means metadata items defined via the META directive can 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 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. Great for applying consistent wrappers around all your templates β kind of like what PRE_PROCESS and POST_PROCESS templates do, but in the "instead of" direction. π¦
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. You can inspect its metadata items, and you can process the template by specifying 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>
<!-- begin content -->
[% PROCESS $template %]
<!-- end content -->
<hr>
© 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>
<!-- begin content -->
<h1>The Foo Page</h1>
Welcome to the Foo Page, blah blah blah
<!-- end content -->
<hr>
© Copyright 2000 Fred Foo
</body>
</html>
WRAPPER
The WRAPPER option lets you specify one or more templates to wrap around the output of the main page template. Like a little cozy blanket for your HTML. π«Ά
The main template gets processed first (or any PROCESS template(s)), and the output generated is then passed as the content variable to the WRAPPER template(s) as they get processed.
my $template = Template->new({
WRAPPER => 'wrapper',
});
# process 'foo' then wrap in 'wrapper'
$template->process('foo', { message => 'Hello World!' });
wrapper:
<wrapper>
[% content %]
</wrapper>
foo:
This is the foo file!
Message: [% message %]
And the output generated from this example is:
<wrapper>
This is the foo file!
Message: Hello World!
</wrapper>
Literal perfection. β¨
WRAPPERβ okay so you can literally stack these π just set the value to a reference to a list of templates instead of a single one. TheWRAPPERtemplates get processed in reverse order, and the output of each one gets passed along to the next (or the previous, depending on how you're looking at it π) as the'content'variable. Sounds like a whole complicated thing but honestly the end result is that it just "Does The Right Thing" to make wrapper templates nest in the exact order you specify. iconic behavior tbh.
my $template = Template->new({
WRAPPER => [ 'outer', 'inner' ],
};
# process 'foo' then wrap in 'inner', then in 'outer'
$template->process('foo', { message => 'Hello World!' });
outer:
<outer>
[% content %]
</outer>
inner:
<inner>
[% content %]
</inner>
The output generated is then:
<outer>
<inner>
This is the foo file!
Message: Hello World!
</inner>
</outer>
One side-effect of the "inside-out" processing of the WRAPPER configuration item (and also the WRAPPER directive, bestie, both of them π«Ά) is that any variables set in the template being wrapped will be visible to the template doing the wrapping, but not the other way around. One-way glass situation β¨
You can use this to good effect in allowing page templates to set pre-defined values which are then used in the wrapper templates. Like, our main page template foo might look like this:
foo:
[% page = {
title = 'Foo Page'
subtitle = 'Everything There is to Know About Foo'
author = 'Frank Oliver Octagon'
}
%]
<p>
Welcome to the page that tells you everything about foo
blah blah blah...
</p>
The foo template is processed before the wrapper template, meaning that the page data structure will be defined for use in the wrapper template. chef's kiss π§βπ³π
wrapper:
<html>
<head>
<title>[% page.title %]</title>
</head>
<body>
<h1>[% page.title %]</h1>
<h2>[% page.subtitle %]</h1>
<h3>by [% page.author %]</h3>
[% content %]
</body>
</html>
It achieves the same effect as defining META items which are then accessed via the template variable (which you are still free to use within WRAPPER templates, no cap π), but it gives you more flexibility in the type and complexity of data that you can define.
π ERROR π
The ERROR (or ERRORS if you prefer, both work, we don't gatekeep π) 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. it's giving safety net β¨
If specified as a single value then that template will be processed for all uncaught exceptions. simple as that π
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 template 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. pick your fave fr fr π«Ά
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. equal treatment, we love to see it π
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 single string (i.e. user.passwd is parsed as 'user'.'passwd'). lowkey a trap, don't fall for it π
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 $template 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 template. 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. the way this just sorts itself out πβ¨
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 Template::Context object,
$context->throw('user.passwd', 'Incorrect Password');
$context->throw('Incorrect Password'); # type 'undef'
or from Perl code by calling die() with a Template::Exception object,
die (Template::Exception->new('user.denied', 'Invalid 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. magic fr π§
die "I'm sorry Dave, I can't do that";
β οΈ Note that the'undef'we're talking about here is a literal string rather than Perl'sundefused to represent undefined values. do not confuse them bestie, they are not the same thing π
β¨ Template Runtime Options β¨
Okay bestie, this is the runtime era of the config β the stuff that controls what actually happens when your template gets processed. Buckle up, because EVAL_PERL is about to get real cautious with us. π
π₯ EVAL_PERL π₯
This flag is the vibe check for whether PERL and/or RAWPERL blocks should be evaluated. Itβs disabled by default, and if the Template Toolkit runs into any PERL or RAWPERL blocks while itβs off, it raises exceptions of type "perl" with the message "EVAL_PERL not set". Not me getting yelled at by the parser. π
Important caveat though: any RAWPERL blocks should always contain valid Perl code, regardless 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. So like, the flag doesnβt save you from syntax errors, bestie. π
When youβre using compiled templates (peep βCaching and Compiling Optionsβ), EVAL_PERL has an affect when the template is compiled, and again when the template is subsequently processed, possibly in a different context to the one that compiled it. Yes, itβs giving double duty. β¨
If 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.
So basically: you must have EVAL_PERL set if you want your compiled templates to include PERL and RAWPERL blocks. No cap.
At some point in the future, using a different invocation 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 regardless of the runtime EVAL_PERL status. RAWPERL said main character energy, honestly. π
Regular PERL blocks are a little more cautious, however. 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. But note: 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. So 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. Periodt. π«Ά
π OUTPUT π
Default output location or handler. This may be specified 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.
GLOBor 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 supports the
print()method. This latter option includes theApache::Requestobject 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 => \$output,
});
example 3 (file handle):
open (TOUT, ">", $file) || die "$file: $!\n";
my $template = Template->new({
OUTPUT => \*TOUT,
});
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 can 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, \$output);
$t->process($file, $vars, \*MYGLOB);
$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. Slay, organized output. π
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.
π STRICT π
By default the Template Toolkit will silently ignore the use of undefined variables (a bad design decision that I regret). The original author said that, not me. π
When the STRICT option is set, the use of any undefined variables or values will cause an exception to be thrown. The exception will have a "type" of var.undef and a message of the form undefined variable: xxx. No more sneaky undefs sliding under the radar. β¨
my $template = Template->new(
STRICT => 1
);
π DEBUG π
The DEBUG option can be used to enable debugging within the various different modules that comprise the Template Toolkit. The Template::Constants module defines a set of DEBUG_XXXX constants which can be combined using the logical OR operator, "|".
use Template::Constants qw( :debug );
my $template = Template->new({
DEBUG => DEBUG_PARSER | DEBUG_PROVIDER,
});
For convenience, you can also provide a string containing a list of lower case debug options, separated by any non-word characters. Cute and chaotic. π
my $template = Template->new({
DEBUG => 'parser, provider',
});
The following DEBUG_XXXX flags can be used:
πΈ DEBUG_SERVICE πΈ
Enables general debugging messages for the Template::Service module.
πΊ DEBUG_CONTEXT πΊ
Enables general debugging messages for the Template::Context module.
π DEBUG_PROVIDER π
Enables general debugging messages for the Template::Provider module.
π§ DEBUG_PLUGINS π§
Enables general debugging messages for the Template::Plugins module.
π DEBUG_FILTERS π
Enables general debugging messages for the Template::Filters module.
β DEBUG_PARSER β
This flag causes the Template::Parser to generate debugging messages that show the Perl code generated by parsing and compiling each template.
π DEBUG_UNDEF π
This option causes the Template Toolkit to throw an "undef" error whenever it encounters an undefined variable value.
π DEBUG_DIRS π
This option causes the Template Toolkit to generate comments indicating the source file, line and original text of each directive in the template. These comments are embedded in the template output using the format defined in the DEBUG_FORMAT configuration item, or a simple default format if unspecified.
For example, the following template fragment:
Hello World
would generate this output:
## input text line 1 : ##
Hello
## input text line 2 : World ##
World
π₯ DEBUG_ALL π₯
Enables all debugging messages. All of them. Every last one. π
π¦ DEBUG_CALLER π¦
This option causes all debug messages that arenβt newline terminated to have the file name and line number of the caller appended to them.
π DEBUG_FORMAT π
The DEBUG_FORMAT option can be used to specify a format string for the debugging messages generated via the DEBUG_DIRS option described above. Any occurrences 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 interpolating those tokens as variables. Important bestie detail. π«Ά
my $template = Template->new({
DEBUG => 'dirs',
DEBUG_FORMAT => '<!-- $file line $line : [% $text %] -->',
});
The following template fragment:
[% 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
okay so bestie, Template::Provider caches compiled templates so it does not have to re-parse template files or blocks every single time they get used. the CACHE_SIZE option is literally the cap on how many compiled templates the module should keep in the cache.
by default, CACHE_SIZE is undefined and all compiled templates are cached. when you set it to any positive value, the cache gets 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 gets discarded to make room for the new one. bye queen π
you can set CACHE_SIZE 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
});
as well as caching templates as they are found, Template::Provider also implements negative caching to keep track of templates that are not found. this lets the provider quickly decline a request for a template it has previously failed to locate, saving the effort of going to look for it again. super useful when an INCLUDE_PATH includes multiple providers, because it ensures the request gets passed down through the providers as quickly as possible. efficiency slay β¨
β±οΈ STAT_TTL
this value controls how long Template::Provider will keep a template cached in memory before checking to see if the source template has changed.
my $provider = Template::Provider->new({
STAT_TTL => 60, # one minute
});
the default value is 1 (second). you'll probably want to set this higher if you're running the Template Toolkit inside a persistent web server application (e.g. mod_perl). for example, set it to 60 and the provider will only look for changes to templates once a minute at most. however, during development (or any time you're making frequent changes to templates) you'll probably want to keep it set to a low value so you don't have to wait for the provider to notice that your templates have changed. we love a low-maintenance queen π
π§ 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 persistence). 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 COMPILE_EXT extension will be written to the same directory 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 automatically reload and reuse compiled files when it finds them on disk. if the corresponding source file has been modified since the compiled version was written, then it will load and re-compile the source and write a new compiled version to disk. keeping it fresh, no cap π«Ά
this form of cache persistence offers significant benefits 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. periodt π
π 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 they live 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/templates:/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 saved in the relevant COMPILE_DIR directory. organized and iconic π
on Win32 platforms a filename may be 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 prevent an illegal filename being generated. any colon in COMPILE_DIR elements will be left intact. for example:
# Win32 only
my $template = Template->new({
DELIMITER => ';',
COMPILE_DIR => 'C:/TT2/Cache',
INCLUDE_PATH => 'C:/TT2/Templates;D:/My Templates',
});
this would create the following cache directories:
C:/TT2/Cache/C/TT2/Templates
C:/TT2/Cache/D/My Templates
π Plugins and Filters π
Okay bestie, this is the little accessory collection for Template Toolkit: plugins and filters. Not me being obsessed with custom modules, but likeβ¦ you can absolutely make this yours. π«Ά
π 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, format, cgi, etc.) which map to their corresponding 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 recommended convention is to specify these plugin names in lower case. The Template Toolkit first looks for an exact case-sensitive match and then tries the lower case conversion of the name specified.
[% USE Foo %] # look for 'Foo' then 'foo'
If you define all your PLUGINS with lower case names then they will be located regardless of how the user specifies the name in the USE directive. If, on the other hand, you define your PLUGINS with upper or mixed case names then the name specified in the USE directive must match the case exactly.
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 correct Perl module name which can be successfully loaded.
The PLUGIN_BASE can be specified as a reference to an array of module namespaces, or as a single value which is automatically converted to a list. The default PLUGIN_BASE value (Template::Plugin) is then added to the end of this list.
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' ],
});
template:
[% USE Foo %] # => MyOrg::Template::Plugin::Foo
or YourOrg::Template::Plugin::Foo
or Template::Plugin::Foo
If you don't want the default Template::Plugin namespace added to the end of the PLUGIN_BASE, then set the $Template::Plugins::PLUGIN_BASE variable to a false value before calling the new() Template#new() constructor method. This is shown in the example below where the Foo plugin is located as My::Plugin::Foo or Your::Plugin::Foo but not as Template::Plugin::Foo.
example 3:
use Template::Plugins;
$Template::Plugins::PLUGIN_BASE = '';
my $template = Template->new({
PLUGIN_BASE => [ 'My::Plugin',
'Your::Plugin' ],
});
template:
[% USE Foo %] # => My::Plugin::Foo
or Your::Plugin::Foo
π¦ LOAD_PERL
If a plugin cannot be loaded using the PLUGINS or PLUGIN_BASE approaches then the provider can make a final attempt to load the module without prepending any prefix to the module path. This allows regular Perl modules (i.e. those that don't reside in the Template::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 components.
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 argument.
Plugin modules should provide a load() class method (or inherit the default one from the Template::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 convention then a simple plugin wrapper can be written to interface to it.
π FILTERS
The FILTERS option can be used to specify custom filters which can then be used with the FILTER directive like any other. These are added to the standard filters which are available by default. Filters specified 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 reference and a flag which indicates if the filter is static (0) or dynamic (1). A filter may also be specified 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 Template::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 statically. The subroutine reference is simply returned when that particular filter is requested. The subroutine is called to filter the output of a template block which is passed as the only argument. The subroutine 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("\nBlah blah blah.\n");
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 Template::Context object is passed as the first parameter, followed by any additional parameters specified. The subroutine should return another subroutine reference (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("\nBlah blah blah.\n");
See the FILTER directive for further examples.
β¨ Customisation and Extension β¨
LOAD_TEMPLATES
okay so the LOAD_TEMPLATES option is literally your plug for handing over a reference to a list of Template::Provider objects (or sub-classes of it) that are gonna take full responsibility for loading and compiling templates. bestie, it's giving delegation and we love that.
my $template = Template->new({
LOAD_TEMPLATES => [
MyOrg::Template::Provider->new({ ... }),
Template::Provider->new({ ... }),
],
});
when a PROCESS, INCLUDE or WRAPPER directive shows up, the named template might 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 (peep the Template::Context template() method for the whole discussion of BLOCK locality) then each of the LOAD_TEMPLATES provider objects gets queried in turn via the fetch() method to see if it can supply the required template. it's a whole relay race, honestly.
each provider can return a compiled template, an error, or straight-up decline to service the request β in which case the responsibility gets 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 to parse or process the contents of the template file. periodt.
if LOAD_TEMPLATES is undefined, a single default provider will be instantiated using the current configuration parameters. for example, the Template::Provider INCLUDE_PATH option can be specified in the Template configuration and will be correctly passed to the provider's constructor method. slay.
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 instantiating template plugin objects. the Template::Context plugin() method queries each provider in turn in a "Chain of Responsibility" as per the template() and filter() methods. iykyk.
my $template = Template->new({
LOAD_PLUGINS => [
MyOrg::Template::Plugins->new({ ... }),
Template::Plugins->new({ ... }),
],
});
by default, a single Template::Plugins object is created using the current configuration hash. configuration items destined for the Template::Plugins constructor may be added to the Template constructor. no cap.
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. it's giving teamwork makes the dream work.
my $template = Template->new({
LOAD_FILTERS => [
MyTemplate::Filters->new(),
Template::Filters->new(),
],
});
by default, a single Template::Filters object is created for the LOAD_FILTERS list. iconic.
TOLERANT
the TOLERANT flag is used by the various Template Toolkit provider modules (Template::Provider, Template::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. like, it's not mad, it's just disappointed.
when the TOLERANT 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 tolerated failure or a genuine disinclination to comply, then a '"<resource> not found"' exception is raised. and that's the tea π«.
SERVICE
a reference to a Template::Service object, or sub-class thereof, to which the Template module should delegate. if unspecified, a Template::Service object is automatically created using the current configuration hash. main character energy honestly.
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 template are processed. a Template::Context object is passed as the only parameter to the Perl subroutines that represent "compiled" template documents. template subroutines make callbacks into the context object to access Template Toolkit functionality β for example, to INCLUDE or PROCESS another template (include() and process() methods, respectively), to USE a plugin (plugin()) or instantiate a filter (filter()) or to access the stash (stash()) which manages variable definitions via the get() and set() methods. it's the whole backstage pass of the operation.
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. she's the keeper of the variables, the vibe curator, the queen of the stash.
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. cute.
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 created automatically and then used by the Template::Provider whenever a template is loaded and requires compilation. the PARSER option can be used to provide a reference to an alternate parser object. it's giving custom build, and we respect it.
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 constructed and used by the Template Toolkit. literally inventing your own language, we love a creative genius moment.
source templates are compiled to Perl code by the Template::Parser using the Template::Grammar (by default) to define the language structure and semantics. compiled 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 environment (other than the usual time and memory constraints). okay but that's actually so cool.
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. the lore is real.
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 comfortably familiar. bestie, if you're built different in that way, go off.
by default, an instance of the default Template::Grammar will be created and used automatically if a GRAMMAR item isn't specified.
use MyOrg::Template::Grammar;
my $template = Template->new({
GRAMMAR = MyOrg::Template::Grammar->new();
});
okay that's the whole customisation and extension situation, and honestly? she's thorough. thanks for sticking with the whole page, bestie β you understood the assignment. π π
made with care, perl v5.42.0, dated 2024-06-23, and officially signed off as Templat...:Config(3) β¨π¦
π¦ where this page comes from
- opensuse-leap 16.0: perl-Template-Toolkit 3.102.0-bp160.1.13 Β· Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-Template-Toolkit 3.102.0-bp160.1.13 Β· Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-Template-Toolkit 3.102.0-bp160.1.13 Β· Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-Template-Toolkit 3.102.0-bp160.1.13 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms