1 #============================================================= -*-perl-*-
3 # Template::Manual::Config
6 # Andy Wardley <abw@wardley.org>
9 # Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
11 # This module is free software; you can redistribute it and/or
12 # modify it under the same terms as Perl itself.
14 #========================================================================
18 Template::Manual::Config - Configuration options
20 =head1 Template Style and Parsing Options
22 =head2 START_TAG, END_TAG
24 The C<START_TAG> and C<END_TAG> options are used to specify character
25 sequences or regular expressions that mark the start and end of a
26 template directive. The default values for C<START_TAG> and C<END_TAG> are
27 'C<[%>' and 'C<%]>' respectively, giving us the familiar directive style:
31 Any Perl regex characters can be used and therefore should be escaped
32 (or use the Perl C<quotemeta> function) if they are intended to
33 represent literal characters.
35 my $template = Template->new({
36 START_TAG => quotemeta('<+'),
37 END_TAG => quotemeta('+>'),
44 The C<TAGS> directive can also be used to set the C<START_TAG> and C<END_TAG> values
45 on a per-template file basis.
51 The C<TAG_STYLE> option can be used to set both C<START_TAG> and C<END_TAG>
52 according to pre-defined tag styles.
54 my $template = Template->new({
60 template [% ... %] (default)
61 template1 [% ... %] or %% ... %% (TT version 1)
62 metatext %% ... %% (Text::MetaText)
63 star [* ... *] (TT alternate)
66 mason <% ... > (HTML::Mason)
67 html <!-- ... --> (HTML comments)
69 Any values specified for C<START_TAG> and/or C<END_TAG> will override
70 those defined by a C<TAG_STYLE>.
72 The C<TAGS> directive may also be used to set a C<TAG_STYLE>
75 <!-- INCLUDE header -->
77 =head2 PRE_CHOMP, POST_CHOMP
79 Anything outside a directive tag is considered plain text and is
80 generally passed through unaltered (but see the L<INTERPOLATE> option).
81 This includes all whitespace and newlines characters surrounding
82 directive tags. Directives that don't generate any output will leave
83 gaps in the output document.
97 The C<PRE_CHOMP> and C<POST_CHOMP> options can help to clean up some of this
98 extraneous whitespace. Both are disabled by default.
100 my $template = Template-E<gt>new({
105 With C<PRE_CHOMP> set to C<1>, the newline and whitespace preceding a directive
106 at the start of a line will be deleted. This has the effect of
107 concatenating a line that starts with a directive onto the end of the
120 With C<POST_CHOMP> set to C<1>, any whitespace after a directive up to and
121 including the newline will be deleted. This has the effect of joining
122 a line that ends with a directive onto the start of the next line.
124 If C<PRE_CHOMP> or C<POST_CHOMP> is set to C<2>, all whitespace including any
125 number of newline will be removed and replaced with a single space.
126 This is useful for HTML, where (usually) a contiguous block of
127 whitespace is rendered the same as a single space.
129 With C<PRE_CHOMP> or C<POST_CHOMP> set to C<3>, all adjacent whitespace
130 (including newlines) will be removed entirely.
132 These values are defined as C<CHOMP_NONE>, C<CHOMP_ONE>, C<CHOMP_COLLAPSE> and
133 C<CHOMP_GREEDY> constants in the L<Template::Constants> module. C<CHOMP_ALL>
134 is also defined as an alias for C<CHOMP_ONE> to provide backwards
135 compatability with earlier version of the Template Toolkit.
137 Additionally the chomp tag modifiers listed below may also be used for
138 the C<PRE_CHOMP> and C<POST_CHOMP> configuration.
140 my $template = Template->new({
145 C<PRE_CHOMP> and C<POST_CHOMP> can be activated for individual directives by
146 placing a 'C<->' immediately at the start and/or end of the directive.
148 [% FOREACH user IN userlist %]
152 This has the same effect as C<CHOMP_ONE> in removing all whitespace
153 before or after the directive up to and including the newline. The
154 template will be processed as if written:
156 [% FOREACH user IN userlist %][% user %][% END %]
158 To remove all whitespace including any number of newlines, use the 'C<~>'
161 [% FOREACH user IN userlist %]
167 To collapse all whitespace to a single space, use the 'C<=>' character.
169 [% FOREACH user IN userlist %]
175 Here the template is processed as if written:
177 [% FOREACH user IN userlist %] [% user %] [% END %]
179 If you have C<PRE_CHOMP> or C<POST_CHOMP> set as configuration options then
180 you can use 'C<+>' to disable any chomping options (i.e. leave the
181 whitespace intact) on a per-directive basis.
183 [% FOREACH user IN userlist %]
187 With C<POST_CHOMP> set to C<CHOMP_ONE>, the above example would be parsed as
190 [% FOREACH user IN userlist %]User: [% user %]
193 For reference, the C<PRE_CHOMP> and C<POST_CHOMP> configuration options may be
194 set to any of the following:
196 Constant Value Tag Modifier
197 ----------------------------------
205 The C<TRIM> option can be set to have any leading and trailing whitespace
206 automatically removed from the output of all template files and C<BLOCK>s.
208 By example, the following C<BLOCK> definition
214 will be processed is as "C<\nLine 1 of foo\n>". When C<INCLUDE>d, the surrounding
215 newlines will also be introduced.
229 With the C<TRIM> option set to any true value, the leading and trailing
230 newlines (which count as whitespace) will be removed from the output
237 The C<TRIM> option is disabled (C<0>) by default.
241 The C<INTERPOLATE> flag, when set to any true value will cause variable
242 references in plain text (i.e. not surrounded by C<START_TAG> and C<END_TAG>)
243 to be recognised and interpolated accordingly.
245 my $template = Template->new({
249 Variables should be prefixed by a 'C<$>' to identify them. Curly braces
250 can be used in the familiar Perl/shell style to explicitly scope the
251 variable name where required.
254 <a href="http://[% server %]/[% help %]">
255 <img src="[% images %]/help.gif"></a>
259 <a href="http://$server/$help">
260 <img src="$images/help.gif"></a>
263 # explicit scoping with { }
264 <img src="$images/${icon.next}.gif">
266 Note that a limitation in Perl's regex engine restricts the maximum length
267 of an interpolated template to around 32 kilobytes or possibly less. Files
268 that exceed this limit in size will typically cause Perl to dump core with
269 a segmentation fault. If you routinely process templates of this size
270 then you should disable C<INTERPOLATE> or split the templates in several
271 smaller files or blocks which can then be joined backed together via
272 C<PROCESS> or C<INCLUDE>.
276 By default, directive keywords should be expressed in UPPER CASE. The
277 C<ANYCASE> option can be set to allow directive keywords to be specified
280 # ANYCASE => 0 (default)
281 [% INCLUDE foobar %] # OK
282 [% include foobar %] # ERROR
283 [% include = 10 %] # OK, 'include' is a variable
286 [% INCLUDE foobar %] # OK
287 [% include foobar %] # OK
288 [% include = 10 %] # ERROR, 'include' is reserved word
290 One side-effect of enabling C<ANYCASE> is that you cannot use a variable
291 of the same name as a reserved word, regardless of case. The reserved
294 GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER
295 IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
296 USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
297 TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP
298 CLEAR TO STEP AND OR NOT MOD DIV END
300 The only lower case reserved words that cannot be used for variables,
301 regardless of the C<ANYCASE> option, are the operators:
305 =head1 Template Files and Blocks
309 The C<INCLUDE_PATH> is used to specify one or more directories in which
310 template files are located. When a template is requested that isn't
311 defined locally as a C<BLOCK>, each of the C<INCLUDE_PATH> directories is
312 searched in turn to locate the template file. Multiple directories
313 can be specified as a reference to a list or as a single string where
314 each directory is delimited by 'C<:>'.
316 my $template = Template->new({
317 INCLUDE_PATH => '/usr/local/templates',
320 my $template = Template->new({
321 INCLUDE_PATH => '/usr/local/templates:/tmp/my/templates',
324 my $template = Template->new({
325 INCLUDE_PATH => [ '/usr/local/templates',
326 '/tmp/my/templates' ],
329 On Win32 systems, a little extra magic is invoked, ignoring delimiters
330 that have 'C<:>' followed by a 'C</>' or 'C<\>'. This avoids confusion when using
331 directory names like 'C<C:\Blah Blah>'.
333 When specified as a list, the C<INCLUDE_PATH> path can contain elements
334 which dynamically generate a list of C<INCLUDE_PATH> directories. These
335 generator elements can be specified as a reference to a subroutine or
336 an object which implements a C<paths()> method.
338 my $template = Template->new({
339 INCLUDE_PATH => [ '/usr/local/templates',
341 My::IncPath::Generator->new( ... ) ],
344 Each time a template is requested and the C<INCLUDE_PATH> examined, the
345 subroutine or object method will be called. A reference to a list of
346 directories should be returned. Generator subroutines should report
347 errors using C<die()>. Generator objects should return undef and make an
348 error available via its C<error()> method.
352 sub incpath_generator {
356 return \@list_of_directories;
359 die "cannot generate INCLUDE_PATH...\n";
365 package My::IncPath::Generator;
367 # Template::Base (or Class::Base) provides error() method
369 use base qw( Template::Base );
377 return \@list_of_directories;
380 return $self->error("cannot generate INCLUDE_PATH...\n");
388 Used to provide an alternative delimiter character sequence for
389 separating paths specified in the C<INCLUDE_PATH>. The default
390 value for C<DELIMITER> is 'C<:>'.
392 my $template = Template->new({
394 INCLUDE_PATH => 'C:/HERE/NOW; D:/THERE/THEN',
397 On Win32 systems, the default delimiter is a little more intelligent,
398 splitting paths only on 'C<:>' characters that aren't followed by a 'C</>'.
399 This means that the following should work as planned, splitting the
400 C<INCLUDE_PATH> into 2 separate directories, C<C:/foo> and C<C:/bar>.
403 my $template = Template->new({
404 INCLUDE_PATH => 'C:/Foo:C:/Bar'
407 However, if you're using Win32 then it's recommended that you
408 explicitly set the C<DELIMITER> character to something else (e.g. 'C<;>')
409 rather than rely on this subtle magic.
413 The C<ABSOLUTE> flag is used to indicate if templates specified with
414 absolute filenames (e.g. 'C</foo/bar>') should be processed. It is
415 disabled by default and any attempt to load a template by such a
416 name will cause a 'C<file>' exception to be raised.
418 my $template = Template->new({
422 # this is why it's disabled by default
423 [% INSERT /etc/passwd %]
425 On Win32 systems, the regular expression for matching absolute
426 pathnames is tweaked slightly to also detect filenames that start
427 with a driver letter and colon, such as:
433 The C<RELATIVE> flag is used to indicate if templates specified with
434 filenames relative to the current directory (e.g. 'C<./foo/bar>' or
435 'C<../../some/where/else>') should be loaded. It is also disabled by
436 default, and will raise a 'C<file>' error if such template names are
439 my $template = Template->new({
443 [% INCLUDE ../logs/error.log %]
447 The C<DEFAULT> option can be used to specify a default template which should
448 be used whenever a specified template can't be found in the C<INCLUDE_PATH>.
450 my $template = Template->new({
451 DEFAULT => 'notfound.html',
454 If a non-existant template is requested through the Template
455 L<process()|Template#process()> method, or by an C<INCLUDE>, C<PROCESS> or
456 C<WRAPPER> directive, then the C<DEFAULT> template will instead be processed, if
457 defined. Note that the C<DEFAULT> template is not used when templates are
458 specified with absolute or relative filenames, or as a reference to a input
459 file handle or text string.
463 The C<BLOCKS> option can be used to pre-define a default set of template
464 blocks. These should be specified as a reference to a hash array
465 mapping template names to template text, subroutines or L<Template::Document>
468 my $template = Template->new({
470 header => 'The Header. [% title %]',
471 footer => sub { return $some_output_text },
472 another => Template::Document->new({ ... }),
478 The VIEWS option can be used to define one or more L<Template::View>
479 objects. They can be specified as a reference to a hash array or list
482 my $template = Template->new({
484 my_view => { prefix => 'my_templates/' },
488 Be aware of the fact that Perl's hash array are unordered, so if you want to
489 specify multiple views of which one or more are based on other views, then
490 you should use a list reference to preserve the order of definition.
492 my $template = Template->new({
494 bottom => { prefix => 'bottom/' },
495 middle => { prefix => 'middle/', base => 'bottom' },
496 top => { prefix => 'top/', base => 'middle' },
502 The C<AUTO_RESET> option is set by default and causes the local C<BLOCKS>
503 cache for the L<Template::Context> object to be reset on each call to the
504 Template L<process()|Template#process()> method. This ensures that any C<BLOCK>s
505 defined within a template will only persist until that template is finished
506 processing. This prevents C<BLOCK>s defined in one processing request from
507 interfering with other independent requests subsequently processed by the same
510 The C<BLOCKS> item may be used to specify a default set of block definitions
511 for the L<Template::Context> object. Subsequent C<BLOCK> definitions in
512 templates will over-ride these but they will be reinstated on each reset if
513 C<AUTO_RESET> is enabled (default), or if the L<Template::Context>
514 L<reset()|Template::Context#reset()> method is called.
518 The template processor will raise a file exception if it detects
519 direct or indirect recursion into a template. Setting this option to
520 any true value will allow templates to include each other recursively.
522 =head1 Template Variables
526 The C<VARIABLES> option (or C<PRE_DEFINE> - they're equivalent) can be used
527 to specify a hash array of template variables that should be used to
528 pre-initialise the stash when it is created. These items are ignored
529 if the C<STASH> item is defined.
531 my $template = Template->new({
533 title => 'A Demo Page',
534 author => 'Joe Random Hacker',
541 my $template = Template->new({
543 title => 'A Demo Page',
544 author => 'Joe Random Hacker',
551 The C<CONSTANTS> option can be used to specify a hash array of template
552 variables that are compile-time constants. These variables are
553 resolved once when the template is compiled, and thus don't require
554 further resolution at runtime. This results in significantly faster
555 processing of the compiled templates and can be used for variables that
556 don't change from one request to the next.
558 my $template = Template->new({
560 title => 'A Demo Page',
561 author => 'Joe Random Hacker',
566 =head2 CONSTANT_NAMESPACE
568 Constant variables are accessed via the C<constants> namespace by
571 [% constants.title %]
573 The C<CONSTANTS_NAMESPACE> option can be set to specify an alternate
576 my $template = Template->new({
578 title => 'A Demo Page',
581 CONSTANTS_NAMESPACE => 'const',
584 In this case the constants would then be accessed as:
590 The constant folding mechanism described above is an example of a
591 namespace handler. Namespace handlers can be defined to provide
592 alternate parsing mechanisms for variables in different namespaces.
594 Under the hood, the L<Template> module converts a constructor configuration
597 my $template = Template->new({
599 title => 'A Demo Page',
602 CONSTANTS_NAMESPACE => 'const',
607 my $template = Template->new({
609 const => Template:::Namespace::Constants->new({
610 title => 'A Demo Page',
616 You can use this mechanism to define multiple constant namespaces, or
617 to install custom handlers of your own.
619 my $template = Template->new({
621 site => Template:::Namespace::Constants->new({
622 title => "Wardley's Widgets",
625 author => Template:::Namespace::Constants->new({
626 name => 'Andy Wardley',
627 email => 'abw@andywardley.com',
629 voodoo => My::Namespace::Handler->new( ... ),
633 Now you have two constant namespaces, for example:
638 as well as your own custom namespace handler installed for the 'voodoo'
643 See L<Template::Namespace::Constants>
644 for an example of what a namespace handler looks like on the inside.
646 =head1 Template Processing Options
648 The following options are used to specify any additional templates that should
649 be processed before, after, around or instead of the template passed as the
650 first argument to the L<Template> L<process()|Template#process()> method.
651 These options can be perform various useful tasks such as adding standard
652 headers or footers to all pages, wrapping page output in other templates,
653 pre-defining variables or performing initialisation or cleanup tasks,
654 automatically generating page summary information, navigation elements, and so
657 The task of processing the template is delegated internally to the
658 L<Template::Service> module which, unsurprisingly, also has a
659 L<process()|Template::Service#process()> method. Any templates defined by the
660 C<PRE_PROCESS> option are processed first and any output generated is added to
661 the output buffer. Then the main template is processed, or if one or more
662 C<PROCESS> templates are defined then they are instead processed in turn. In this
663 case, one of the C<PROCESS> templates is responsible for processing the main
664 template, by a directive such as:
666 [% PROCESS $template %]
668 The output of processing the main template or the C<PROCESS> template(s)
669 is then wrapped in any C<WRAPPER> templates, if defined. C<WRAPPER>
670 templates don't need to worry about explicitly processing the template
671 because it will have been done for them already. Instead C<WRAPPER>
672 templates access the content they are wrapping via the C<content>
679 This output generated from processing the main template, and/or any
680 C<PROCESS> or C<WRAPPER> templates is added to the output buffer. Finally,
681 any C<POST_PROCESS> templates are processed and their output is also
682 added to the output buffer which is then returned.
684 If the main template throws an exception during processing then any relevant
685 template(s) defined via the C<ERROR> option will be processed instead. If
686 defined and successfully processed, the output from the error template will be
687 added to the output buffer in place of the template that generated the error
688 and processing will continue, applying any C<WRAPPER> and C<POST_PROCESS>
689 templates. If no relevant C<ERROR> option is defined, or if the error occurs
690 in one of the C<PRE_PROCESS>, C<WRAPPER> or C<POST_PROCESS> templates, then
691 the process will terminate immediately and the error will be returned.
693 =head2 PRE_PROCESS, POST_PROCESS
695 These values may be set to contain the name(s) of template files
696 (relative to C<INCLUDE_PATH>) which should be processed immediately
697 before and/or after each template. These do not get added to
698 templates processed into a document via directives such as C<INCLUDE>,
699 C<PROCESS>, C<WRAPPER> etc.
701 my $template = Template->new({
702 PRE_PROCESS => 'header',
703 POST_PROCESS => 'footer',
706 Multiple templates may be specified as a reference to a list. Each is
707 processed in the order defined.
709 my $template = Template->new({
710 PRE_PROCESS => [ 'config', 'header' ],
711 POST_PROCESS => 'footer',
714 Alternately, multiple template may be specified as a single string,
715 delimited by 'C<:>'. This delimiter string can be changed via the
718 my $template = Template->new({
719 PRE_PROCESS => 'config:header',
720 POST_PROCESS => 'footer',
723 The C<PRE_PROCESS> and C<POST_PROCESS> templates are evaluated in the same
724 variable context as the main document and may define or update
725 variables for subsequent use.
729 [% # set some site-wide variables
736 [% DEFAULT title = 'My Funky Web Site' %]
739 <title>[% title %]</title>
741 <body bgcolor="[% bgcolor %]">
746 Version [% version %]
750 The L<Template::Document> object representing the main template being processed
751 is available within C<PRE_PROCESS> and C<POST_PROCESS> templates as the C<template>
752 variable. Metadata items defined via the C<META> directive may be accessed
755 $template->process('mydoc.html', $vars);
759 [% META title = 'My Document Title' %]
767 <title>[% template.title %]</title>
769 <body bgcolor="[% bgcolor %]">
773 The C<PROCESS> option may be set to contain the name(s) of template files
774 (relative to C<INCLUDE_PATH>) which should be processed instead of the main
775 template passed to the L<Template> L<process()|Template#process()> method.
776 This can be used to apply consistent wrappers around all templates, similar to
777 the use of C<PRE_PROCESS> and C<POST_PROCESS> templates.
779 my $template = Template->new({
780 PROCESS => 'content',
783 # processes 'content' instead of 'foo.html'
784 $template->process('foo.html');
786 A reference to the original template is available in the C<template>
787 variable. Metadata items can be inspected and the template can be
788 processed by specifying it as a variable reference (i.e. prefixed by
789 C<$>) to an C<INCLUDE>, C<PROCESS> or C<WRAPPER> directive.
795 <title>[% template.title %]</title>
798 <!-- begin content -->
799 [% PROCESS $template %]
802 © Copyright [% template.copyright %]
809 title = 'The Foo Page'
811 copyright = '2000 Fred Foo'
813 <h1>[% template.title %]</h1>
814 Welcome to the Foo Page, blah blah blah
820 <title>The Foo Page</title>
823 <!-- begin content -->
824 <h1>The Foo Page</h1>
825 Welcome to the Foo Page, blah blah blah
828 © Copyright 2000 Fred Foo
834 The C<WRAPPER> option can be used to specify one or more templates which
835 should be used to wrap around the output of the main page template.
836 The main template is processed first (or any C<PROCESS> template(s)) and
837 the output generated is then passed as the C<content> variable to the
838 C<WRAPPER> template(s) as they are processed.
840 my $template = Template->new({
841 WRAPPER => 'wrapper',
844 # process 'foo' then wrap in 'wrapper'
845 $template->process('foo', { message => 'Hello World!' });
855 This is the foo file!
856 Message: [% message %]
858 The output generated from this example is:
861 This is the foo file!
862 Message: Hello World!
865 You can specify more than one C<WRAPPER> template by setting the value to
866 be a reference to a list of templates. The C<WRAPPER> templates will be
867 processed in reverse order with the output of each being passed to the
868 next (or previous, depending on how you look at it) as the 'content'
869 variable. It sounds complicated, but the end result is that it just
870 "Does The Right Thing" to make wrapper templates nest in the order you
873 my $template = Template->new({
874 WRAPPER => [ 'outer', 'inner' ],
877 # process 'foo' then wrap in 'inner', then in 'outer'
878 $template->process('foo', { message => 'Hello World!' });
892 The output generated is then:
896 This is the foo file!
897 Message: Hello World!
901 One side-effect of the "inside-out" processing of the C<WRAPPER>
902 configuration item (and also the C<WRAPPER> directive) is that any
903 variables set in the template being wrapped will be visible to the
904 template doing the wrapping, but not the other way around.
906 You can use this to good effect in allowing page templates to set
907 pre-defined values which are then used in the wrapper templates. For
908 example, our main page template 'foo' might look like this:
914 subtitle = 'Everything There is to Know About Foo'
915 author = 'Frank Oliver Octagon'
920 Welcome to the page that tells you everything about foo
924 The C<foo> template is processed before the wrapper template meaning
925 that the C<page> data structure will be defined for use in the wrapper
932 <title>[% page.title %]</title>
935 <h1>[% page.title %]</h1>
936 <h2>[% page.subtitle %]</h1>
937 <h3>by [% page.author %]</h3>
942 It achieves the same effect as defining C<META> items which are then
943 accessed via the C<template> variable (which you are still free to
944 use within C<WRAPPER> templates), but gives you more flexibility in
945 the type and complexity of data that you can define.
949 The C<ERROR> (or C<ERRORS> if you prefer) configuration item can be used to
950 name a single template or specify a hash array mapping exception types
951 to templates which should be used for error handling. If an uncaught
952 exception is raised from within a template then the appropriate error
953 template will instead be processed.
955 If specified as a single value then that template will be processed
956 for all uncaught exceptions.
958 my $template = Template->new({
959 ERROR => 'error.html'
962 If the C<ERROR> item is a hash reference the keys are assumed to be
963 exception types and the relevant template for a given exception will
964 be selected. A C<default> template may be provided for the general
965 case. Note that C<ERROR> can be pluralised to C<ERRORS> if you find
966 it more appropriate in this case.
968 my $template = Template->new({
970 user => 'user/index.html',
971 dbi => 'error/database',
972 default => 'error/default',
976 In this example, any C<user> exceptions thrown will cause the
977 F<user/index.html> template to be processed, C<dbi> errors are handled
978 by F<error/database> and all others by the F<error/default> template.
979 Any C<PRE_PROCESS> and/or C<POST_PROCESS> templates will also be applied
980 to these error templates.
982 Note that exception types are hierarchical and a C<foo> handler will
983 catch all C<foo.*> errors (e.g. C<foo.bar>, C<foo.bar.baz>) if a more
984 specific handler isn't defined. Be sure to quote any exception types
985 that contain periods to prevent Perl concatenating them into a single
986 string (i.e. C<user.passwd> is parsed as C<'user'.'passwd'>).
988 my $template = Template->new({
990 'user.login' => 'user/login.html',
991 'user.passwd' => 'user/badpasswd.html',
992 'user' => 'user/index.html',
993 'default' => 'error/default',
997 In this example, any template processed by the C<$template> object, or
998 other templates or code called from within, can raise a C<user.login>
999 exception and have the service redirect to the F<user/login.html>
1000 template. Similarly, a C<user.passwd> exception has a specific
1001 handling template, F<user/badpasswd.html>, while all other C<user> or
1002 C<user.*> exceptions cause a redirection to the F<user/index.html> page.
1003 All other exception types are handled by F<error/default>.
1005 Exceptions can be raised in a template using the C<THROW> directive,
1007 [% THROW user.login 'no user id: please login' %]
1009 or by calling the L<throw()|Template::Context#throw()> method on the
1010 current L<Template::Context> object,
1012 $context->throw('user.passwd', 'Incorrect Password');
1013 $context->throw('Incorrect Password'); # type 'undef'
1015 or from Perl code by calling C<die()> with a L<Template::Exception> object,
1017 die (Template::Exception->new('user.denied', 'Invalid User ID'));
1019 or by simply calling L<die()> with an error string. This is
1020 automagically caught and converted to an exception of 'C<undef>'
1021 type which can then be handled in the usual way.
1023 die "I'm sorry Dave, I can't do that";
1025 Note that the 'C<undef>' we're talking about here is a literal string
1026 rather than Perl's C<undef> used to represent undefined values.
1028 =head1 Template Runtime Options
1032 This flag is used to indicate if C<PERL> and/or C<RAWPERL> blocks should be
1033 evaluated. It is disabled by default and any C<PERL> or C<RAWPERL> blocks
1034 encountered will raise exceptions of type 'C<perl>' with the message
1035 'C<EVAL_PERL not set>'. Note however that any C<RAWPERL> blocks should
1036 always contain valid Perl code, regardless of the C<EVAL_PERL> flag. The
1037 parser will fail to compile templates that contain invalid Perl code
1038 in C<RAWPERL> blocks and will throw a 'C<file>' exception.
1040 When using compiled templates (see
1041 L<Caching and Compiling Options>),
1042 the C<EVAL_PERL> has an affect when the template is compiled, and again
1043 when the templates is subsequently processed, possibly in a different
1044 context to the one that compiled it.
1046 If the C<EVAL_PERL> is set when a template is compiled, then all C<PERL> and
1047 C<RAWPERL> blocks will be included in the compiled template. If the
1048 C<EVAL_PERL> option isn't set, then Perl code will be generated which
1049 B<always> throws a 'C<perl>' exception with the message 'C<EVAL_PERL not
1050 set>' B<whenever> the compiled template code is run.
1052 Thus, you must have C<EVAL_PERL> set if you want your compiled templates
1053 to include C<PERL> and C<RAWPERL> blocks.
1055 At some point in the future, using a different invocation of the
1056 Template Toolkit, you may come to process such a pre-compiled
1057 template. Assuming the C<EVAL_PERL> option was set at the time the
1058 template was compiled, then the output of any C<RAWPERL> blocks will be
1059 included in the compiled template and will get executed when the
1060 template is processed. This will happen regardless of the runtime
1061 C<EVAL_PERL> status.
1063 Regular C<PERL> blocks are a little more cautious, however. If the
1064 C<EVAL_PERL> flag isn't set for the I<current> context, that is, the
1065 one which is trying to process it, then it will throw the familiar 'C<perl>'
1066 exception with the message, 'C<EVAL_PERL not set>'.
1068 Thus you can compile templates to include C<PERL> blocks, but optionally
1069 disable them when you process them later. Note however that it is
1070 possible for a C<PERL> block to contain a Perl "C<BEGIN { # some code }>"
1071 block which will always get run regardless of the runtime C<EVAL_PERL>
1072 status. Thus, if you set C<EVAL_PERL> when compiling templates, it is
1073 assumed that you trust the templates to Do The Right Thing. Otherwise
1074 you must accept the fact that there's no bulletproof way to prevent
1075 any included code from trampling around in the living room of the
1076 runtime environment, making a real nuisance of itself if it really
1077 wants to. If you don't like the idea of such uninvited guests causing
1078 a bother, then you can accept the default and keep C<EVAL_PERL> disabled.
1082 Default output location or handler. This may be specified as one of:
1083 a file name (relative to C<OUTPUT_PATH>, if defined, or the current
1084 working directory if not specified absolutely); a file handle
1085 (e.g. C<GLOB> or L<IO::Handle>) opened for writing; a reference to a text
1086 string to which the output is appended (the string isn't cleared); a
1087 reference to a subroutine which is called, passing the output text as
1088 an argument; as a reference to an array, onto which the content will be
1089 C<push()>ed; or as a reference to any object that supports the C<print()>
1090 method. This latter option includes the C<Apache::Request> object which
1091 is passed as the argument to Apache/mod_perl handlers.
1093 example 1 (file name):
1095 my $template = Template->new({
1096 OUTPUT => "/tmp/foo",
1099 example 2 (text string):
1102 my $template = Template->new({
1106 example 3 (file handle):
1108 open (TOUT, "> $file") || die "$file: $!\n";
1109 my $template = Template->new({
1113 example 4 (subroutine):
1115 sub output { my $out = shift; print "OUTPUT: $out" }
1116 my $template = Template->new({
1120 example 5 (array reference):
1122 my $template = Template->new({
1126 example 6 (Apache/mod_perl handler):
1130 my $t = Template->new({
1136 The default C<OUTPUT> location be overridden by passing a third parameter to
1137 the L<Template> L<process()|Template#process()> method. This can be specified
1138 as any of the above argument types.
1140 $t->process($file, $vars, "/tmp/foo");
1141 $t->process($file, $vars, \$output);
1142 $t->process($file, $vars, \*MYGLOB);
1143 $t->process($file, $vars, \@output);
1144 $t->process($file, $vars, $r); # Apache::Request
1149 The C<OUTPUT_PATH> allows a directory to be specified into which output
1150 files should be written. An output file can be specified by the
1151 C<OUTPUT> option, or passed by name as the third parameter to the
1152 L<Template> L<process()|Template#process()> method.
1154 my $template = Template->new({
1155 INCLUDE_PATH => "/tmp/src",
1156 OUTPUT_PATH => "/tmp/dest",
1163 foreach my $file ('foo.html', 'bar.html') {
1164 $template->process($file, $vars, $file)
1165 || die $template->error();
1168 This example will read the input files F</tmp/src/foo.html> and
1169 F</tmp/src/bar.html> and write the processed output to F</tmp/dest/foo.html>
1170 and F</tmp/dest/bar.html>, respectively.
1174 By default the Template Toolkit will silently ignore the use of undefined
1175 variables (a bad design decision that I regret).
1177 When the C<STRICT> option is set, the use of any undefined variables or
1178 values will cause an exception to be throw. The exception will have a
1179 C<type> of C<var.undefined> and a message of the form
1180 "undefined variable: xxx".
1182 my $template = Template->new(
1188 The C<DEBUG> option can be used to enable debugging within the various
1189 different modules that comprise the Template Toolkit. The
1190 L<Template::Constants> module defines a set of
1191 C<DEBUG_XXXX> constants which can be combined using the logical OR
1194 use Template::Constants qw( :debug );
1196 my $template = Template->new({
1197 DEBUG => DEBUG_PARSER | DEBUG_PROVIDER,
1200 For convenience, you can also provide a string containing a list
1201 of lower case debug options, separated by any non-word characters.
1203 my $template = Template->new({
1204 DEBUG => 'parser, provider',
1207 The following C<DEBUG_XXXX> flags can be used:
1213 Enables general debugging messages for the
1214 L<Template::Service> module.
1218 Enables general debugging messages for the
1219 L<Template::Context> module.
1221 =item DEBUG_PROVIDER
1223 Enables general debugging messages for the
1224 L<Template::Provider> module.
1228 Enables general debugging messages for the
1229 L<Template::Plugins> module.
1233 Enables general debugging messages for the
1234 L<Template::Filters> module.
1238 This flag causes the L<Template::Parser> to generate
1239 debugging messages that show the Perl code generated by parsing and
1240 compiling each template.
1244 This option causes the Template Toolkit to throw an 'C<undef>' error
1245 whenever it encounters an undefined variable value.
1249 This option causes the Template Toolkit to generate comments
1250 indicating the source file, line and original text of each directive
1251 in the template. These comments are embedded in the template output
1252 using the format defined in the C<DEBUG_FORMAT> configuration item, or a
1253 simple default format if unspecified.
1255 For example, the following template fragment:
1259 would generate this output:
1261 ## input text line 1 : ##
1263 ## input text line 2 : World ##
1268 Enables all debugging messages.
1272 This option causes all debug messages that aren't newline terminated
1273 to have the file name and line number of the caller appended to them.
1279 The C<DEBUG_FORMAT> option can be used to specify a format string for the
1280 debugging messages generated via the C<DEBUG_DIRS> option described
1281 above. Any occurances of C<$file>, C<$line> or C<$text> will be
1282 replaced with the current file name, line or directive text,
1283 respectively. Notice how the format is single quoted to prevent Perl
1284 from interpolating those tokens as variables.
1286 my $template = Template->new({
1288 DEBUG_FORMAT => '<!-- $file line $line : [% $text %] -->',
1291 The following template fragment:
1296 would then generate this output:
1298 <!-- input text line 2 : [% foo = 'World' %] -->
1299 Hello <!-- input text line 3 : [% foo %] -->World
1301 The DEBUG directive can also be used to set a debug format within
1304 [% DEBUG format '<!-- $file line $line : [% $text %] -->' %]
1306 =head1 Caching and Compiling Options
1310 The L<Template::Provider> module caches compiled templates to avoid the need
1311 to re-parse template files or blocks each time they are used. The C<CACHE_SIZE>
1312 option is used to limit the number of compiled templates that the module
1315 By default, the C<CACHE_SIZE> is undefined and all compiled templates are
1316 cached. When set to any positive value, the cache will be limited to
1317 storing no more than that number of compiled templates. When a new
1318 template is loaded and compiled and the cache is full (i.e. the number
1319 of entries == C<CACHE_SIZE>), the least recently used compiled template
1320 is discarded to make room for the new one.
1322 The C<CACHE_SIZE> can be set to C<0> to disable caching altogether.
1324 my $template = Template->new({
1325 CACHE_SIZE => 64, # only cache 64 compiled templates
1328 my $template = Template->new({
1329 CACHE_SIZE => 0, # don't cache any compiled templates
1332 As well as caching templates as they are found, the L<Template::Provider>
1333 also implements negative caching to keep track of templates that are
1334 I<not> found. This allows the provider to quickly decline a request
1335 for a template that it has previously failed to locate, saving the effort
1336 of going to look for it again. This is useful when an C<INCLUDE_PATH> includes
1337 multiple providers, ensuring that the request is passed down through the
1338 providers as quickly as possible.
1342 This value can be set to control how long the L<Template::Provider> will keep a
1343 template cached in memory before checking to see if the source template has
1346 my $provider = Template::Provider->new({
1347 STAT_TTL => 60, # one minute
1350 The default value is 1 (second). You'll probably want to set this to a higher
1351 value if you're running the Template Toolkit inside a persistent web server
1352 application (e.g. mod_perl). For example, set it to 60 and the provider will
1353 only look for changes to templates once a minute at most. However, during
1354 development (or any time you're making frequent changes to templates) you'll
1355 probably want to keep it set to a low value so that you don't have to wait
1356 for the provider to notice that your templates have changed.
1360 From version 2 onwards, the Template Toolkit has the ability to
1361 compile templates to Perl code and save them to disk for subsequent
1362 use (i.e. cache persistence). The C<COMPILE_EXT> option may be
1363 provided to specify a filename extension for compiled template files.
1364 It is undefined by default and no attempt will be made to read or write
1365 any compiled template files.
1367 my $template = Template->new({
1368 COMPILE_EXT => '.ttc',
1371 If C<COMPILE_EXT> is defined (and C<COMPILE_DIR> isn't, see below) then compiled
1372 template files with the C<COMPILE_EXT> extension will be written to the same
1373 directory from which the source template files were loaded.
1375 Compiling and subsequent reuse of templates happens automatically
1376 whenever the C<COMPILE_EXT> or C<COMPILE_DIR> options are set. The Template
1377 Toolkit will automatically reload and reuse compiled files when it
1378 finds them on disk. If the corresponding source file has been modified
1379 since the compiled version as written, then it will load and re-compile
1380 the source and write a new compiled version to disk.
1382 This form of cache persistence offers significant benefits in terms of
1383 time and resources required to reload templates. Compiled templates can
1384 be reloaded by a simple call to Perl's C<require()>, leaving Perl to handle
1385 all the parsing and compilation. This is a Good Thing.
1389 The C<COMPILE_DIR> option is used to specify an alternate directory root
1390 under which compiled template files should be saved.
1392 my $template = Template->new({
1393 COMPILE_DIR => '/tmp/ttc',
1396 The C<COMPILE_EXT> option may also be specified to have a consistent file
1397 extension added to these files.
1399 my $template1 = Template->new({
1400 COMPILE_DIR => '/tmp/ttc',
1401 COMPILE_EXT => '.ttc1',
1404 my $template2 = Template->new({
1405 COMPILE_DIR => '/tmp/ttc',
1406 COMPILE_EXT => '.ttc2',
1409 When C<COMPILE_EXT> is undefined, the compiled template files have the
1410 same name as the original template files, but reside in a different
1413 Each directory in the C<INCLUDE_PATH> is replicated in full beneath the
1414 C<COMPILE_DIR> directory. This example:
1416 my $template = Template->new({
1417 COMPILE_DIR => '/tmp/ttc',
1418 INCLUDE_PATH => '/home/abw/templates:/usr/share/templates',
1421 would create the following directory structure:
1423 /tmp/ttc/home/abw/templates/
1424 /tmp/ttc/usr/share/templates/
1426 Files loaded from different C<INCLUDE_PATH> directories will have their
1427 compiled forms save in the relevant C<COMPILE_DIR> directory.
1429 On Win32 platforms a filename may by prefixed by a drive letter and
1432 C:/My Templates/header
1434 The colon will be silently stripped from the filename when it is added
1435 to the C<COMPILE_DIR> value(s) to prevent illegal filename being generated.
1436 Any colon in C<COMPILE_DIR> elements will be left intact. For example:
1439 my $template = Template->new({
1441 COMPILE_DIR => 'C:/TT2/Cache',
1442 INCLUDE_PATH => 'C:/TT2/Templates;D:/My Templates',
1445 This would create the following cache directories:
1447 C:/TT2/Cache/C/TT2/Templates
1448 C:/TT2/Cache/D/My Templates
1450 =head1 Plugins and Filters
1454 The C<PLUGINS> options can be used to provide a reference to a hash array
1455 that maps plugin names to Perl module names. A number of standard
1456 plugins are defined (e.g. C<table>, C<format>, C<cgi>, etc.) which map to
1457 their corresponding C<Template::Plugin::*> counterparts. These can be
1458 redefined by values in the C<PLUGINS> hash.
1460 my $template = Template->new({
1462 cgi => 'MyOrg::Template::Plugin::CGI',
1463 foo => 'MyOrg::Template::Plugin::Foo',
1464 bar => 'MyOrg::Template::Plugin::Bar',
1468 The recommended convention is to specify these plugin names in lower
1469 case. The Template Toolkit first looks for an exact case-sensitive
1470 match and then tries the lower case conversion of the name specified.
1472 [% USE Foo %] # look for 'Foo' then 'foo'
1474 If you define all your C<PLUGINS> with lower case names then they will be
1475 located regardless of how the user specifies the name in the USE
1476 directive. If, on the other hand, you define your C<PLUGINS> with upper
1477 or mixed case names then the name specified in the C<USE> directive must
1478 match the case exactly.
1480 The C<USE> directive is used to create plugin objects and does so by calling
1481 the L<plugin()|Template::Context#plugin()> method on the current
1482 L<Template::Context> object. If the plugin name is defined in the C<PLUGINS>
1483 hash then the corresponding Perl module is loaded via C<require()>. The
1484 context then calls the L<load()|Template::Plugin#load()> class method which
1485 should return the class name (default and general case) or a prototype object
1486 against which the L<new()|Template::Plugin#new()> method can be called to
1487 instantiate individual plugin objects.
1489 If the plugin name is not defined in the C<PLUGINS> hash then the
1490 C<PLUGIN_BASE> and/or C<LOAD_PERL> options come into effect.
1494 If a plugin is not defined in the C<PLUGINS> hash then the C<PLUGIN_BASE> is used
1495 to attempt to construct a correct Perl module name which can be successfully
1498 The C<PLUGIN_BASE> can be specified as a reference to an array of module
1499 namespaces, or as a single value which is automatically converted to a
1500 list. The default C<PLUGIN_BASE> value (C<Template::Plugin>) is then added
1501 to the end of this list.
1505 my $template = Template->new({
1506 PLUGIN_BASE => 'MyOrg::Template::Plugin',
1509 [% USE Foo %] # => MyOrg::Template::Plugin::Foo
1510 or Template::Plugin::Foo
1514 my $template = Template->new({
1515 PLUGIN_BASE => [ 'MyOrg::Template::Plugin',
1516 'YourOrg::Template::Plugin' ],
1521 [% USE Foo %] # => MyOrg::Template::Plugin::Foo
1522 or YourOrg::Template::Plugin::Foo
1523 or Template::Plugin::Foo
1525 If you don't want the default C<Template::Plugin> namespace added to the
1526 end of the C<PLUGIN_BASE>, then set the C<$Template::Plugins::PLUGIN_BASE>
1527 variable to a false value before calling the L<new()|Template> L<Template#new()>
1528 constructor method. This is shown in the example below where the
1529 C<Foo> plugin is located as C<My::Plugin::Foo> or C<Your::Plugin::Foo> but not
1530 as C<Template::Plugin::Foo>.
1534 use Template::Plugins;
1535 $Template::Plugins::PLUGIN_BASE = '';
1537 my $template = Template->new({
1538 PLUGIN_BASE => [ 'My::Plugin',
1544 [% USE Foo %] # => My::Plugin::Foo
1545 or Your::Plugin::Foo
1549 If a plugin cannot be loaded using the C<PLUGINS> or C<PLUGIN_BASE>
1550 approaches then the provider can make a final attempt to load the
1551 module without prepending any prefix to the module path. This allows
1552 regular Perl modules (i.e. those that don't reside in the
1553 L<Template::Plugin> or some other such namespace) to be loaded and used
1556 By default, the C<LOAD_PERL> option is set to C<0> and no attempt will be made
1557 to load any Perl modules that aren't named explicitly in the C<PLUGINS>
1558 hash or reside in a package as named by one of the C<PLUGIN_BASE>
1561 Plugins loaded using the C<PLUGINS> or C<PLUGIN_BASE> receive a reference to
1562 the current context object as the first argument to the
1563 L<new()|Template::Plugin#new()> constructor. Modules loaded using C<LOAD_PERL>
1564 are assumed to not conform to the plugin interface. They must provide a C<new()>
1565 class method for instantiating objects but it will not receive a reference to
1566 the context as the first argument.
1568 Plugin modules should provide a L<load()|Template::Plugin#load()> class method
1569 (or inherit the default one from the L<Template::Plugin> base class) which is
1570 called the first time the plugin is loaded. Regular Perl modules need not. In
1571 all other respects, regular Perl objects and Template Toolkit plugins are
1574 If a particular Perl module does not conform to the common, but not
1575 unilateral, C<new()> constructor convention then a simple plugin wrapper
1576 can be written to interface to it.
1580 The C<FILTERS> option can be used to specify custom filters which can
1581 then be used with the C<FILTER> directive like any other. These are
1582 added to the standard filters which are available by default. Filters
1583 specified via this option will mask any standard filters of the same
1586 The C<FILTERS> option should be specified as a reference to a hash array
1587 in which each key represents the name of a filter. The corresponding
1588 value should contain a reference to an array containing a subroutine
1589 reference and a flag which indicates if the filter is static (C<0>) or
1590 dynamic (C<1>). A filter may also be specified as a solitary subroutine
1591 reference and is assumed to be static.
1593 $template = Template->new({
1595 'sfilt1' => \&static_filter, # static
1596 'sfilt2' => [ \&static_filter, 0 ], # same as above
1597 'dfilt1' => [ \&dyanamic_filter_factory, 1 ],
1601 Additional filters can be specified at any time by calling the
1602 L<define_filter()|Template::Context#define_filter()> method on the current
1603 L<Template::Context> object. The method accepts a filter name, a reference to a
1604 filter subroutine and an optional flag to indicate if the filter is dynamic.
1606 my $context = $template->context();
1607 $context->define_filter('new_html', \&new_html);
1608 $context->define_filter('new_repeat', \&new_repeat, 1);
1610 Static filters are those where a single subroutine reference is used
1611 for all invocations of a particular filter. Filters that don't accept
1612 any configuration parameters (e.g. C<html>) can be implemented
1613 statically. The subroutine reference is simply returned when that
1614 particular filter is requested. The subroutine is called to filter
1615 the output of a template block which is passed as the only argument.
1616 The subroutine should return the modified text.
1620 # do something to modify $text...
1624 The following template fragment:
1630 is approximately equivalent to:
1632 &static_filter("\nBlah blah blah.\n");
1634 Filters that can accept parameters (e.g. C<truncate>) should be
1635 implemented dynamically. In this case, the subroutine is taken to be
1636 a filter 'factory' that is called to create a unique filter subroutine
1637 each time one is requested. A reference to the current
1638 L<Template::Context> object is passed as the first parameter, followed by
1639 any additional parameters specified. The subroutine should return
1640 another subroutine reference (usually a closure) which implements the
1643 sub dynamic_filter_factory {
1644 my ($context, @args) = @_;
1648 # do something to modify $text...
1653 The following template fragment:
1655 [% FILTER dfilt1(123, 456) %]
1659 is approximately equivalent to:
1661 my $filter = &dynamic_filter_factory($context, 123, 456);
1662 &$filter("\nBlah blah blah.\n");
1664 See the C<FILTER> directive for further examples.
1666 =head1 Customisation and Extension
1668 =head2 LOAD_TEMPLATES
1670 The C<LOAD_TEMPLATES> option can be used to provide a reference to a list
1671 of L<Template::Provider> objects or sub-classes thereof which will take
1672 responsibility for loading and compiling templates.
1674 my $template = Template->new({
1676 MyOrg::Template::Provider->new({ ... }),
1677 Template::Provider->new({ ... }),
1681 When a C<PROCESS>, C<INCLUDE> or C<WRAPPER> directive is encountered, the
1682 named template may refer to a locally defined C<BLOCK> or a file relative to
1683 the C<INCLUDE_PATH> (or an absolute or relative path if the appropriate
1684 C<ABSOLUTE> or C<RELATIVE> options are set). If a C<BLOCK> definition can't be
1685 found (see the L<Template::Context> L<template()|Template::Context#template()>
1686 method for a discussion of C<BLOCK> locality) then each of the
1687 C<LOAD_TEMPLATES> provider objects is queried in turn via the
1688 L<fetch()|Template::Provider#fetch()> method to see if it can supply the
1691 Each provider can return a compiled template, an error, or decline to service
1692 the request in which case the responsibility is passed to the next provider.
1693 If none of the providers can service the request then a 'not found' error is
1694 returned. The same basic provider mechanism is also used for the C<INSERT>
1695 directive but it bypasses any C<BLOCK> definitions and doesn't attempt is to
1696 parse or process the contents of the template file.
1698 If C<LOAD_TEMPLATES> is undefined, a single default provider will be
1699 instantiated using the current configuration parameters. For example, the
1700 L<Template::Provider> C<INCLUDE_PATH> option can be specified in the L<Template>
1701 configuration and will be correctly passed to the provider's constructor
1704 my $template = Template->new({
1705 INCLUDE_PATH => '/here:/there',
1710 The C<LOAD_PLUGINS> options can be used to specify a list of provider objects
1711 (i.e. they implement the L<fetch()|Template::Plugins#fetch()> method) which
1712 are responsible for loading and instantiating template plugin objects. The
1713 L<Template::Context> L<plugin()|Template::Context#plugin()> method queries
1714 each provider in turn in a "Chain of Responsibility" as per the
1715 L<template()|Template::Context#template()> and
1716 L<filter()|Template::Context#filter()> methods.
1718 my $template = Template->new({
1720 MyOrg::Template::Plugins->new({ ... }),
1721 Template::Plugins->new({ ... }),
1725 By default, a single L<Template::Plugins> object is created using the
1726 current configuration hash. Configuration items destined for the
1727 L<Template::Plugins> constructor may be added to the Template
1730 my $template = Template->new({
1731 PLUGIN_BASE => 'MyOrg::Template::Plugins',
1737 The C<LOAD_FILTERS> option can be used to specify a list of provider objects
1738 (i.e. they implement the L<fetch()|Template::Filters#fetch()> method) which
1739 are responsible for returning and/or creating filter subroutines. The
1740 L<Template::Context> L<filter()|Template::Context#filter()> method queries
1741 each provider in turn in a "Chain of Responsibility" as per the
1742 L<template()|Template::Context#template()> and
1743 L<plugin()|Template::Context#plugin()> methods.
1745 my $template = Template->new({
1747 MyTemplate::Filters->new(),
1748 Template::Filters->new(),
1752 By default, a single L<Template::Filters> object is created for the
1753 C<LOAD_FILTERS> list.
1757 The C<TOLERANT> flag is used by the various Template Toolkit provider modules
1758 (L<Template::Provider>, L<Template::Plugins>, L<Template::Filters>) to control
1759 their behaviour when errors are encountered. By default, any errors are
1760 reported as such, with the request for the particular resource (C<template>,
1761 C<plugin>, C<filter>) being denied and an exception raised.
1763 When the C<TOLERANT> flag is set to any true values, errors will be silently
1764 ignored and the provider will instead return C<STATUS_DECLINED>. This allows a
1765 subsequent provider to take responsibility for providing the resource, rather
1766 than failing the request outright. If all providers decline to service the
1767 request, either through tolerated failure or a genuine disinclination to
1768 comply, then a 'C<E<lt>resourceE<gt> not found>' exception is raised.
1772 A reference to a L<Template::Service> object, or sub-class thereof, to which
1773 the L<Template> module should delegate. If unspecified, a L<Template::Service>
1774 object is automatically created using the current configuration hash.
1776 my $template = Template->new({
1777 SERVICE => MyOrg::Template::Service->new({ ... }),
1782 A reference to a L<Template::Context> object which is used to define a
1783 specific environment in which template are processed. A L<Template::Context>
1784 object is passed as the only parameter to the Perl subroutines that represent
1785 "compiled" template documents. Template subroutines make callbacks into the
1786 context object to access Template Toolkit functionality, for example, to to
1787 C<INCLUDE> or C<PROCESS> another template
1788 (L<include()|Template::Context#include()> and
1789 L<process()|Template::Context#process()> methods, respectively), to C<USE> a
1790 plugin (L<plugin()|Template::Context#plugin()>) or instantiate a filter
1791 (L<filter()|Template::Context#filter()>) or to access the stash
1792 (L<stash()|Template::Context#stash()>) which manages variable definitions via
1793 the L<get()|Template::Stash#get()> and L<set()|Template::Stash#set()> methods.
1795 my $template = Template->new({
1796 CONTEXT => MyOrg::Template::Context->new({ ... }),
1801 A reference to a L<Template::Stash> object or sub-class which will take
1802 responsibility for managing template variables.
1804 my $stash = MyOrg::Template::Stash->new({ ... });
1805 my $template = Template->new({
1809 If unspecified, a default stash object is created using the C<VARIABLES>
1810 configuration item to initialise the stash variables.
1812 my $template = Template->new({
1815 name => 'Andy Wardley',
1821 The L<Template::Parser> module implements a parser object for compiling
1822 templates into Perl code which can then be executed. A default object
1823 of this class is created automatically and then used by the
1824 L<Template::Provider> whenever a template is loaded and requires
1825 compilation. The C<PARSER> option can be used to provide a reference to
1826 an alternate parser object.
1828 my $template = Template->new({
1829 PARSER => MyOrg::Template::Parser->new({ ... }),
1834 The C<GRAMMAR> configuration item can be used to specify an alternate
1835 grammar for the parser. This allows a modified or entirely new
1836 template language to be constructed and used by the Template Toolkit.
1838 Source templates are compiled to Perl code by the L<Template::Parser>
1839 using the L<Template::Grammar> (by default) to define the language
1840 structure and semantics. Compiled templates are thus inherently
1841 "compatible" with each other and there is nothing to prevent any
1842 number of different template languages being compiled and used within
1843 the same Template Toolkit processing environment (other than the usual
1844 time and memory constraints).
1846 The L<Template::Grammar> file is constructed from a YACC like grammar
1847 (using C<Parse::YAPP>) and a skeleton module template. These files are
1848 provided, along with a small script to rebuild the grammar, in the
1849 F<parser> sub-directory of the distribution.
1851 You don't have to know or worry about these unless you want to hack on the
1852 template language or define your own variant. There is a F<README> file in the
1853 same directory which provides some small guidance but it is assumed that you
1854 know what you're doing if you venture herein. If you grok LALR parsers, then
1855 you should find it comfortably familiar.
1857 By default, an instance of the default L<Template::Grammar> will be
1858 created and used automatically if a C<GRAMMAR> item isn't specified.
1860 use MyOrg::Template::Grammar;
1862 my $template = Template->new({
1863 GRAMMAR = MyOrg::Template::Grammar->new();
1870 # perl-indent-level: 4
1871 # indent-tabs-mode: nil
1874 # vim: expandtab shiftwidth=4: