1Template::Manual::ConfiUgs(e3r)Contributed Perl DocumentTaetmipolnate::Manual::Config(3)
2
3
4

NAME

6       Template::Manual::Config - Configuration options
7

Template Style and Parsing Options

9   ENCODING
10       The "ENCODING" option specifies the template files' character encoding:
11
12           my $template = Template->new({
13               ENCODING => 'utf8',
14           });
15
16       A template which starts with a Unicode byte order mark (BOM) will have
17       its encoding detected automatically.
18
19   START_TAG, END_TAG
20       The "START_TAG" and "END_TAG" options are used to specify character
21       sequences or regular expressions that mark the start and end of inline
22       template directives.  The default values for "START_TAG" and "END_TAG"
23       are '"[%"' and '"%]"' respectively, giving us the familiar directive
24       style:
25
26           [% example %]
27
28       Any Perl regex characters can be used and therefore should be escaped
29       (or use the Perl "quotemeta" function) if they are intended to
30       represent literal characters.
31
32           my $template = Template->new({
33               START_TAG => quotemeta('<+'),
34               END_TAG   => quotemeta('+>'),
35           });
36
37       Example:
38
39           <+ INCLUDE foobar +>
40
41       The "TAGS" directive can also be used to set the "START_TAG" and
42       "END_TAG" values on a per-template file basis.
43
44           [% TAGS <+ +> %]
45
46   OUTLINE_TAG
47       The "OUTLINE_TAG" option can be used to enable single-line "outline"
48       directives.
49
50           my $template = Template->new({
51               OUTLINE_TAG => '%%',
52           });
53
54       This allows you to use both inline and outline tags like so:
55
56           %% IF user
57           Hello [% user.name %]
58           %% END
59
60       The "OUTLINE_TAG" string (or regex) must appear at the start of a line.
61       The directive continues until the end of the line.  The newline
62       character at the end of the line is considered to be the invisible end-
63       of-directive marker and is removed.
64
65   TAG_STYLE
66       The "TAG_STYLE" option can be used to set both "START_TAG" and
67       "END_TAG" according to pre-defined tag styles.
68
69           my $template = Template->new({
70               TAG_STYLE => 'star',
71           });
72
73       Available styles are:
74
75           template    [% ... %]               (default)
76           template1   [% ... %] or %% ... %%  (TT version 1)
77           metatext    %% ... %%               (Text::MetaText)
78           star        [* ... *]               (TT alternate)
79           php         <? ... ?>               (PHP)
80           asp         <% ... %>               (ASP)
81           mason       <% ...  >               (HTML::Mason)
82           html        <!-- ... -->            (HTML comments)
83
84       The "outline" style uses the default markers for "START_TAG" and
85       "END_TAG" ("[%" and "%]" respectively) and additionally defines
86       "OUTLINE_TAG" to be "%%".
87
88           my $template = Template->new({
89               TAG_STYLE => 'outline',
90           });
91
92       This allows you to use both inline and outline tags like so:
93
94           %% IF user
95           Hello [% user.name %]
96           %% END
97
98       Any values specified for "START_TAG", "END_TAG" and/or "OUTLINE_TAG"
99       will override those defined by a "TAG_STYLE".
100
101       The "TAGS" directive may also be used to set a "TAG_STYLE"
102
103           [% TAGS html %]
104           <!-- INCLUDE header -->
105
106   PRE_CHOMP, POST_CHOMP
107       Anything outside a directive tag is considered plain text and is
108       generally passed through unaltered (but see the INTERPOLATE option).
109       This includes all whitespace and newlines characters surrounding
110       directive tags.  Directives that don't generate any output will leave
111       gaps in the output document.
112
113       Example:
114
115           Foo
116           [% a = 10 %]
117           Bar
118
119       Output:
120
121           Foo
122
123           Bar
124
125       The "PRE_CHOMP" and "POST_CHOMP" options can help to clean up some of
126       this extraneous whitespace.  Both are disabled by default.
127
128           my $template = Template-E<gt>new({
129               PRE_CHOMP  => 1,
130               POST_CHOMP => 1,
131           });
132
133       With "PRE_CHOMP" set to 1, the newline and whitespace preceding a
134       directive at the start of a line will be deleted.  This has the effect
135       of concatenating a line that starts with a directive onto the end of
136       the previous line.
137
138               Foo <----------.
139                              |
140           ,---(PRE_CHOMP)----'
141           |
142           `-- [% a = 10 %] --.
143                              |
144           ,---(POST_CHOMP)---'
145           |
146           `-> Bar
147
148       With "POST_CHOMP" set to 1, any whitespace after a directive up to and
149       including the newline will be deleted.  This has the effect of joining
150       a line that ends with a directive onto the start of the next line.
151
152       If "PRE_CHOMP" or "POST_CHOMP" is set to 2, all whitespace including
153       any number of newline will be removed and replaced with a single space.
154       This is useful for HTML, where (usually) a contiguous block of
155       whitespace is rendered the same as a single space.
156
157       With "PRE_CHOMP" or "POST_CHOMP" set to 3, all adjacent whitespace
158       (including newlines) will be removed entirely.
159
160       These values are defined as "CHOMP_NONE", "CHOMP_ONE", "CHOMP_COLLAPSE"
161       and "CHOMP_GREEDY" constants in the Template::Constants module.
162       "CHOMP_ALL" is also defined as an alias for "CHOMP_ONE" to provide
163       backwards compatibility with earlier version of the Template Toolkit.
164
165       Additionally the chomp tag modifiers listed below may also be used for
166       the "PRE_CHOMP" and "POST_CHOMP" configuration.
167
168            my $template = Template->new({
169               PRE_CHOMP  => '~',
170               POST_CHOMP => '-',
171            });
172
173       "PRE_CHOMP" and "POST_CHOMP" can be activated for individual directives
174       by placing a '"-"' immediately at the start and/or end of the
175       directive.
176
177           [% FOREACH user IN userlist %]
178              [%- user -%]
179           [% END %]
180
181       This has the same effect as "CHOMP_ONE" in removing all whitespace
182       before or after the directive up to and including the newline.  The
183       template will be processed as if written:
184
185           [% FOREACH user IN userlist %][% user %][% END %]
186
187       To remove all whitespace including any number of newlines, use the
188       '"~"' character instead.
189
190           [% FOREACH user IN userlist %]
191
192              [%~ user ~%]
193
194           [% END %]
195
196       To collapse all whitespace to a single space, use the '"="' character.
197
198           [% FOREACH user IN userlist %]
199
200              [%= user =%]
201
202           [% END %]
203
204       Here the template is processed as if written:
205
206           [% FOREACH user IN userlist %] [% user %] [% END %]
207
208       If you have "PRE_CHOMP" or "POST_CHOMP" set as configuration options
209       then you can use '"+"' to disable any chomping options (i.e.  leave the
210       whitespace intact) on a per-directive basis.
211
212           [% FOREACH user IN userlist %]
213           User: [% user +%]
214           [% END %]
215
216       With "POST_CHOMP" set to "CHOMP_ONE", the above example would be parsed
217       as if written:
218
219           [% FOREACH user IN userlist %]User: [% user %]
220           [% END %]
221
222       For reference, the "PRE_CHOMP" and "POST_CHOMP" configuration options
223       may be set to any of the following:
224
225            Constant      Value   Tag Modifier
226            ----------------------------------
227            CHOMP_NONE      0          +
228            CHOMP_ONE       1          -
229            CHOMP_COLLAPSE  2          =
230            CHOMP_GREEDY    3          ~
231
232   TRIM
233       The "TRIM" option can be set to have any leading and trailing
234       whitespace automatically removed from the output of all template files
235       and "BLOCK"s.
236
237       By example, the following "BLOCK" definition
238
239           [% BLOCK foo %]
240           Line 1 of foo
241           [% END %]
242
243       will be processed is as ""\nLine 1 of foo\n"".  When "INCLUDE"d, the
244       surrounding newlines will also be introduced.
245
246           before
247           [% INCLUDE foo %]
248           after
249
250       Generated output:
251
252           before
253
254           Line 1 of foo
255
256           after
257
258       With the "TRIM" option set to any true value, the leading and trailing
259       newlines (which count as whitespace) will be removed from the output of
260       the "BLOCK".
261
262           before
263           Line 1 of foo
264           after
265
266       The "TRIM" option is disabled (0) by default.
267
268   INTERPOLATE
269       The "INTERPOLATE" flag, when set to any true value will cause variable
270       references in plain text (i.e. not surrounded by "START_TAG" and
271       "END_TAG") to be recognised and interpolated accordingly.
272
273           my $template = Template->new({
274               INTERPOLATE => 1,
275           });
276
277       Variables should be prefixed by a '"$"' to identify them.  Curly braces
278       can be used in the familiar Perl/shell style to explicitly scope the
279       variable name where required.
280
281           # INTERPOLATE => 0
282           <a href="http://[% server %]/[% help %]">
283           <img src="[% images %]/help.gif"></a>
284           [% myorg.name %]
285
286           # INTERPOLATE => 1
287           <a href="http://$server/$help">
288           <img src="$images/help.gif"></a>
289           $myorg.name
290
291           # explicit scoping with {  }
292           <img src="$images/${icon.next}.gif">
293
294       Note that a limitation in Perl's regex engine restricts the maximum
295       length of an interpolated template to around 32 kilobytes or possibly
296       less.  Files that exceed this limit in size will typically cause Perl
297       to dump core with a segmentation fault.  If you routinely process
298       templates of this size then you should disable "INTERPOLATE" or split
299       the templates in several smaller files or blocks which can then be
300       joined backed together via "PROCESS" or "INCLUDE".
301
302   ANYCASE
303       By default, directive keywords should be expressed in UPPER CASE.  The
304       "ANYCASE" option can be set to allow directive keywords to be specified
305       in any case.
306
307           # ANYCASE => 0 (default)
308           [% INCLUDE foobar %]        # OK
309           [% include foobar %]        # ERROR
310           [% include = 10   %]        # OK, 'include' is a variable
311
312           # ANYCASE => 1
313           [% INCLUDE foobar %]        # OK
314           [% include foobar %]        # OK
315           [% include = 10   %]        # ERROR, 'include' is reserved word
316
317       One side-effect of enabling "ANYCASE" is that you cannot use a variable
318       of the same name as a reserved word, regardless of case.  The reserved
319       words are currently:
320
321           GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER
322           IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
323           USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
324           TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP
325           CLEAR TO STEP AND OR NOT MOD DIV END
326
327       The only lower case reserved words that cannot be used for variables,
328       regardless of the "ANYCASE" option, are the operators:
329
330           and or not mod div
331

Template Files and Blocks

333   INCLUDE_PATH
334       The "INCLUDE_PATH" is used to specify one or more directories in which
335       template files are located.  When a template is requested that isn't
336       defined locally as a "BLOCK", each of the "INCLUDE_PATH" directories is
337       searched in turn to locate the template file.  Multiple directories can
338       be specified as a reference to a list or as a single string where each
339       directory is delimited by '":"'.
340
341           my $template = Template->new({
342               INCLUDE_PATH => '/usr/local/templates',
343           });
344
345           my $template = Template->new({
346               INCLUDE_PATH => '/usr/local/templates:/tmp/my/templates',
347           });
348
349           my $template = Template->new({
350               INCLUDE_PATH => [ '/usr/local/templates',
351                                 '/tmp/my/templates' ],
352           });
353
354       On Win32 systems, a little extra magic is invoked, ignoring delimiters
355       that have '":"' followed by a '"/"' or '"\"'.  This avoids confusion
356       when using directory names like '"C:\Blah Blah"'.
357
358       When specified as a list, the "INCLUDE_PATH" path can contain elements
359       which dynamically generate a list of "INCLUDE_PATH" directories.  These
360       generator elements can be specified as a reference to a subroutine or
361       an object which implements a "paths()" method.
362
363           my $template = Template->new({
364               INCLUDE_PATH => [ '/usr/local/templates',
365                                 \&incpath_generator,
366                                 My::IncPath::Generator->new( ... ) ],
367           });
368
369       Each time a template is requested and the "INCLUDE_PATH" examined, the
370       subroutine or object method will be called.  A reference to a list of
371       directories should be returned.  Generator subroutines should report
372       errors using "die()".  Generator objects should return undef and make
373       an error available via its "error()" method.
374
375       For example:
376
377           sub incpath_generator {
378               # ...some code...
379
380               if ($all_is_well) {
381                   return \@list_of_directories;
382               }
383               else {
384                   die "cannot generate INCLUDE_PATH...\n";
385               }
386           }
387
388       or:
389
390           package My::IncPath::Generator;
391
392           # Template::Base (or Class::Base) provides error() method
393           use Template::Base;
394           use base qw( Template::Base );
395
396           sub paths {
397               my $self = shift;
398
399               # ...some code...
400
401               if ($all_is_well) {
402                   return \@list_of_directories;
403               }
404               else {
405                   return $self->error("cannot generate INCLUDE_PATH...\n");
406               }
407           }
408
409           1;
410
411   DELIMITER
412       Used to provide an alternative delimiter character sequence for
413       separating paths specified in the "INCLUDE_PATH".  The default value
414       for "DELIMITER" is '":"'.
415
416           my $template = Template->new({
417               DELIMITER    => '; ',
418               INCLUDE_PATH => 'C:/HERE/NOW; D:/THERE/THEN',
419           });
420
421       On Win32 systems, the default delimiter is a little more intelligent,
422       splitting paths only on '":"' characters that aren't followed by a
423       '"/"'.  This means that the following should work as planned, splitting
424       the "INCLUDE_PATH" into 2 separate directories, "C:/foo" and "C:/bar".
425
426           # on Win32 only
427           my $template = Template->new({
428               INCLUDE_PATH => 'C:/Foo:C:/Bar'
429           });
430
431       However, if you're using Win32 then it's recommended that you
432       explicitly set the "DELIMITER" character to something else (e.g. '";"')
433       rather than rely on this subtle magic.
434
435   ABSOLUTE
436       The "ABSOLUTE" flag is used to indicate if templates specified with
437       absolute filenames (e.g. '"/foo/bar"') should be processed.  It is
438       disabled by default and any attempt to load a template by such a name
439       will cause a '"file"' exception to be raised.
440
441           my $template = Template->new({
442               ABSOLUTE => 1,
443           });
444
445           # this is why it's disabled by default
446           [% INSERT /etc/passwd %]
447
448       On Win32 systems, the regular expression for matching absolute
449       pathnames is tweaked slightly to also detect filenames that start with
450       a driver letter and colon, such as:
451
452           C:/Foo/Bar
453
454   RELATIVE
455       The "RELATIVE" flag is used to indicate if templates specified with
456       filenames relative to the current directory (e.g. '"./foo/bar"' or
457       '"../../some/where/else"') should be loaded.  It is also disabled by
458       default, and will raise a '"file"' error if such template names are
459       encountered.
460
461           my $template = Template->new({
462               RELATIVE => 1,
463           });
464
465           [% INCLUDE ../logs/error.log %]
466
467   DEFAULT
468       The "DEFAULT" option can be used to specify a default template which
469       should be used whenever a specified template can't be found in the
470       "INCLUDE_PATH".
471
472           my $template = Template->new({
473               DEFAULT => 'notfound.html',
474           });
475
476       If a non-existent template is requested through the Template process()
477       method, or by an "INCLUDE", "PROCESS" or "WRAPPER" directive, then the
478       "DEFAULT" template will instead be processed, if defined. Note that the
479       "DEFAULT" template is not used when templates are specified with
480       absolute or relative filenames, or as a reference to a input file
481       handle or text string.
482
483   BLOCKS
484       The "BLOCKS" option can be used to pre-define a default set of template
485       blocks.  These should be specified as a reference to a hash array
486       mapping template names to template text, subroutines or
487       Template::Document objects.
488
489           my $template = Template->new({
490               BLOCKS => {
491                   header  => 'The Header.  [% title %]',
492                   footer  => sub { return $some_output_text },
493                   another => Template::Document->new({ ... }),
494               },
495           });
496
497   VIEWS
498       The VIEWS option can be used to define one or more Template::View
499       objects.  They can be specified as a reference to a hash array or list
500       reference.
501
502           my $template = Template->new({
503               VIEWS => {
504                   my_view => { prefix => 'my_templates/' },
505               },
506           });
507
508       Be aware of the fact that Perl's hash array are unordered, so if you
509       want to specify multiple views of which one or more are based on other
510       views, then you should use a list reference to preserve the order of
511       definition.
512
513           my $template = Template->new({
514               VIEWS => [
515                   bottom => { prefix => 'bottom/' },
516                   middle => { prefix => 'middle/', base => 'bottom' },
517                   top    => { prefix => 'top/',    base => 'middle' },
518               ],
519           });
520
521   AUTO_RESET
522       The "AUTO_RESET" option is set by default and causes the local "BLOCKS"
523       cache for the Template::Context object to be reset on each call to the
524       Template process() method. This ensures that any "BLOCK"s defined
525       within a template will only persist until that template is finished
526       processing. This prevents "BLOCK"s defined in one processing request
527       from interfering with other independent requests subsequently processed
528       by the same context object.
529
530       The "BLOCKS" item may be used to specify a default set of block
531       definitions for the Template::Context object. Subsequent "BLOCK"
532       definitions in templates will over-ride these but they will be
533       reinstated on each reset if "AUTO_RESET" is enabled (default), or if
534       the Template::Context reset() method is called.
535
536   RECURSION
537       The template processor will raise a file exception if it detects direct
538       or indirect recursion into a template.  Setting this option to any true
539       value will allow templates to include each other recursively.
540

Template Variables

542   VARIABLES
543       The "VARIABLES" option (or "PRE_DEFINE" - they're equivalent) can be
544       used to specify a hash array of template variables that should be used
545       to pre-initialise the stash when it is created.  These items are
546       ignored if the "STASH" item is defined.
547
548           my $template = Template->new({
549               VARIABLES => {
550                   title   => 'A Demo Page',
551                   author  => 'Joe Random Hacker',
552                   version => 3.14,
553               },
554           };
555
556       or
557
558           my $template = Template->new({
559               PRE_DEFINE => {
560                   title   => 'A Demo Page',
561                   author  => 'Joe Random Hacker',
562                   version => 3.14,
563               },
564           };
565
566   CONSTANTS
567       The "CONSTANTS" option can be used to specify a hash array of template
568       variables that are compile-time constants.  These variables are
569       resolved once when the template is compiled, and thus don't require
570       further resolution at runtime.  This results in significantly faster
571       processing of the compiled templates and can be used for variables that
572       don't change from one request to the next.
573
574           my $template = Template->new({
575               CONSTANTS => {
576                   title   => 'A Demo Page',
577                   author  => 'Joe Random Hacker',
578                   version => 3.14,
579               },
580           };
581
582   CONSTANT_NAMESPACE
583       Constant variables are accessed via the "constants" namespace by
584       default.
585
586           [% constants.title %]
587
588       The "CONSTANTS_NAMESPACE" option can be set to specify an alternate
589       namespace.
590
591           my $template = Template->new({
592               CONSTANTS => {
593                   title   => 'A Demo Page',
594                   # ...etc...
595               },
596               CONSTANTS_NAMESPACE => 'const',
597           };
598
599       In this case the constants would then be accessed as:
600
601           [% const.title %]
602
603   NAMESPACE
604       The constant folding mechanism described above is an example of a
605       namespace handler.  Namespace handlers can be defined to provide
606       alternate parsing mechanisms for variables in different namespaces.
607
608       Under the hood, the Template module converts a constructor
609       configuration such as:
610
611           my $template = Template->new({
612               CONSTANTS => {
613                   title   => 'A Demo Page',
614                   # ...etc...
615               },
616               CONSTANTS_NAMESPACE => 'const',
617           };
618
619       into one like:
620
621           my $template = Template->new({
622               NAMESPACE => {
623                   const => Template:::Namespace::Constants->new({
624                       title   => 'A Demo Page',
625                       # ...etc...
626                   }),
627               },
628           };
629
630       You can use this mechanism to define multiple constant namespaces, or
631       to install custom handlers of your own.
632
633           my $template = Template->new({
634               NAMESPACE => {
635                   site => Template:::Namespace::Constants->new({
636                       title   => "Wardley's Widgets",
637                       version => 2.718,
638                   }),
639                   author => Template:::Namespace::Constants->new({
640                       name  => 'Andy Wardley',
641                       email => 'abw@andywardley.com',
642                   }),
643                   voodoo => My::Namespace::Handler->new( ... ),
644               },
645           };
646
647       Now you have two constant namespaces, for example:
648
649           [% site.title %]
650           [% author.name %]
651
652       as well as your own custom namespace handler installed for the 'voodoo'
653       namespace.
654
655           [% voodoo.magic %]
656
657       See Template::Namespace::Constants for an example of what a namespace
658       handler looks like on the inside.
659

Template Processing Options

661       The following options are used to specify any additional templates that
662       should be processed before, after, around or instead of the template
663       passed as the first argument to the Template process() method.  These
664       options can be perform various useful tasks such as adding standard
665       headers or footers to all pages, wrapping page output in other
666       templates, pre-defining variables or performing initialisation or
667       cleanup tasks, automatically generating page summary information,
668       navigation elements, and so on.
669
670       The task of processing the template is delegated internally to the
671       Template::Service module which, unsurprisingly, also has a process()
672       method. Any templates defined by the "PRE_PROCESS" option are processed
673       first and any output generated is added to the output buffer. Then the
674       main template is processed, or if one or more "PROCESS" templates are
675       defined then they are instead processed in turn. In this case, one of
676       the "PROCESS" templates is responsible for processing the main
677       template, by a directive such as:
678
679           [% PROCESS $template %]
680
681       The output of processing the main template or the "PROCESS" template(s)
682       is then wrapped in any "WRAPPER" templates, if defined.  "WRAPPER"
683       templates don't need to worry about explicitly processing the template
684       because it will have been done for them already.  Instead "WRAPPER"
685       templates access the content they are wrapping via the "content"
686       variable.
687
688           wrapper before
689           [% content %]
690           wrapper after
691
692       This output generated from processing the main template, and/or any
693       "PROCESS" or "WRAPPER" templates is added to the output buffer.
694       Finally, any "POST_PROCESS" templates are processed and their output is
695       also added to the output buffer which is then returned.
696
697       If the main template throws an exception during processing then any
698       relevant template(s) defined via the "ERROR" option will be processed
699       instead. If defined and successfully processed, the output from the
700       error template will be added to the output buffer in place of the
701       template that generated the error and processing will continue,
702       applying any "WRAPPER" and "POST_PROCESS" templates. If no relevant
703       "ERROR" option is defined, or if the error occurs in one of the
704       "PRE_PROCESS", "WRAPPER" or "POST_PROCESS" templates, then the process
705       will terminate immediately and the error will be returned.
706
707   PRE_PROCESS, POST_PROCESS
708       These values may be set to contain the name(s) of template files
709       (relative to "INCLUDE_PATH") which should be processed immediately
710       before and/or after each template.  These do not get added to templates
711       processed into a document via directives such as "INCLUDE", "PROCESS",
712       "WRAPPER" etc.
713
714           my $template = Template->new({
715               PRE_PROCESS  => 'header',
716               POST_PROCESS => 'footer',
717           };
718
719       Multiple templates may be specified as a reference to a list.  Each is
720       processed in the order defined.
721
722           my $template = Template->new({
723               PRE_PROCESS  => [ 'config', 'header' ],
724               POST_PROCESS => 'footer',
725           };
726
727       Alternately, multiple template may be specified as a single string,
728       delimited by '":"'.  This delimiter string can be changed via the
729       "DELIMITER" option.
730
731           my $template = Template->new({
732               PRE_PROCESS  => 'config:header',
733               POST_PROCESS => 'footer',
734           };
735
736       The "PRE_PROCESS" and "POST_PROCESS" templates are evaluated in the
737       same variable context as the main document and may define or update
738       variables for subsequent use.
739
740       config:
741
742           [% # set some site-wide variables
743              bgcolor = '#ffffff'
744              version = 2.718
745           %]
746
747       header:
748
749           [% DEFAULT title = 'My Funky Web Site' %]
750           <html>
751             <head>
752               <title>[% title %]</title>
753             </head>
754             <body bgcolor="[% bgcolor %]">
755
756       footer:
757
758               <hr>
759               Version [% version %]
760             </body>
761           </html>
762
763       The Template::Document object representing the main template being
764       processed is available within "PRE_PROCESS" and "POST_PROCESS"
765       templates as the "template" variable.  Metadata items defined via the
766       "META" directive may be accessed accordingly.
767
768           $template->process('mydoc.html', $vars);
769
770       mydoc.html:
771
772           [% META title = 'My Document Title' %]
773           blah blah blah
774           ...
775
776       header:
777
778           <html>
779             <head>
780               <title>[% template.title %]</title>
781             </head>
782             <body bgcolor="[% bgcolor %]">
783
784   PROCESS
785       The "PROCESS" option may be set to contain the name(s) of template
786       files (relative to "INCLUDE_PATH") which should be processed instead of
787       the main template passed to the Template process() method.  This can be
788       used to apply consistent wrappers around all templates, similar to the
789       use of "PRE_PROCESS" and "POST_PROCESS" templates.
790
791           my $template = Template->new({
792               PROCESS  => 'content',
793           };
794
795           # processes 'content' instead of 'foo.html'
796           $template->process('foo.html');
797
798       A reference to the original template is available in the "template"
799       variable.  Metadata items can be inspected and the template can be
800       processed by specifying it as a variable reference (i.e. prefixed by
801       "$") to an "INCLUDE", "PROCESS" or "WRAPPER" directive.
802
803       content:
804
805           <html>
806             <head>
807               <title>[% template.title %]</title>
808             </head>
809             <body>
810           <!-- begin content -->
811           [% PROCESS $template %]
812           <!-- end content -->
813               <hr>
814               &copy; Copyright [% template.copyright %]
815             </body>
816           </html>
817
818       foo.html:
819
820           [% META
821              title     = 'The Foo Page'
822              author    = 'Fred Foo'
823              copyright = '2000 Fred Foo'
824           %]
825           <h1>[% template.title %]</h1>
826           Welcome to the Foo Page, blah blah blah
827
828       output:
829
830           <html>
831             <head>
832               <title>The Foo Page</title>
833             </head>
834             <body>
835           <!-- begin content -->
836           <h1>The Foo Page</h1>
837           Welcome to the Foo Page, blah blah blah
838           <!-- end content -->
839               <hr>
840               &copy; Copyright 2000 Fred Foo
841             </body>
842           </html>
843
844   WRAPPER
845       The "WRAPPER" option can be used to specify one or more templates which
846       should be used to wrap around the output of the main page template.
847       The main template is processed first (or any "PROCESS" template(s)) and
848       the output generated is then passed as the "content" variable to the
849       "WRAPPER" template(s) as they are processed.
850
851           my $template = Template->new({
852               WRAPPER => 'wrapper',
853           };
854
855           # process 'foo' then wrap in 'wrapper'
856           $template->process('foo', { message => 'Hello World!' });
857
858       wrapper:
859
860           <wrapper>
861           [% content %]
862           </wrapper>
863
864       foo:
865
866           This is the foo file!
867           Message: [% message %]
868
869       The output generated from this example is:
870
871           <wrapper>
872           This is the foo file!
873           Message: Hello World!
874           </wrapper>
875
876       You can specify more than one "WRAPPER" template by setting the value
877       to be a reference to a list of templates.  The "WRAPPER" templates will
878       be processed in reverse order with the output of each being passed to
879       the next (or previous, depending on how you look at it) as the
880       'content' variable.  It sounds complicated, but the end result is that
881       it just "Does The Right Thing" to make wrapper templates nest in the
882       order you specify.
883
884           my $template = Template->new({
885               WRAPPER => [ 'outer', 'inner' ],
886           };
887
888           # process 'foo' then wrap in 'inner', then in 'outer'
889           $template->process('foo', { message => 'Hello World!' });
890
891       outer:
892
893           <outer>
894           [% content %]
895           </outer>
896
897       inner:
898
899           <inner>
900           [% content %]
901           </inner>
902
903       The output generated is then:
904
905           <outer>
906           <inner>
907           This is the foo file!
908           Message: Hello World!
909           </inner>
910           </outer>
911
912       One side-effect of the "inside-out" processing of the "WRAPPER"
913       configuration item (and also the "WRAPPER" directive) is that any
914       variables set in the template being wrapped will be visible to the
915       template doing the wrapping, but not the other way around.
916
917       You can use this to good effect in allowing page templates to set pre-
918       defined values which are then used in the wrapper templates.  For
919       example, our main page template 'foo' might look like this:
920
921       foo:
922
923           [% page = {
924                  title    = 'Foo Page'
925                  subtitle = 'Everything There is to Know About Foo'
926                  author   = 'Frank Oliver Octagon'
927              }
928           %]
929
930           <p>
931           Welcome to the page that tells you everything about foo
932           blah blah blah...
933           </p>
934
935       The "foo" template is processed before the wrapper template meaning
936       that the "page" data structure will be defined for use in the wrapper
937       template.
938
939       wrapper:
940
941           <html>
942             <head>
943               <title>[% page.title %]</title>
944             </head>
945             <body>
946               <h1>[% page.title %]</h1>
947               <h2>[% page.subtitle %]</h1>
948               <h3>by [% page.author %]</h3>
949               [% content %]
950             </body>
951           </html>
952
953       It achieves the same effect as defining "META" items which are then
954       accessed via the "template" variable (which you are still free to use
955       within "WRAPPER" templates), but gives you more flexibility in the type
956       and complexity of data that you can define.
957
958   ERROR
959       The "ERROR" (or "ERRORS" if you prefer) configuration item can be used
960       to name a single template or specify a hash array mapping exception
961       types to templates which should be used for error handling.  If an
962       uncaught exception is raised from within a template then the
963       appropriate error template will instead be processed.
964
965       If specified as a single value then that template will be processed for
966       all uncaught exceptions.
967
968           my $template = Template->new({
969               ERROR => 'error.html'
970           });
971
972       If the "ERROR" item is a hash reference the keys are assumed to be
973       exception types and the relevant template for a given exception will be
974       selected.  A "default" template may be provided for the general case.
975       Note that "ERROR" can be pluralised to "ERRORS" if you find it more
976       appropriate in this case.
977
978           my $template = Template->new({
979               ERRORS => {
980                   user     => 'user/index.html',
981                   dbi      => 'error/database',
982                   default  => 'error/default',
983               },
984           });
985
986       In this example, any "user" exceptions thrown will cause the
987       user/index.html template to be processed, "dbi" errors are handled by
988       error/database and all others by the error/default template.  Any
989       "PRE_PROCESS" and/or "POST_PROCESS" templates will also be applied to
990       these error templates.
991
992       Note that exception types are hierarchical and a "foo" handler will
993       catch all "foo.*" errors (e.g. "foo.bar", "foo.bar.baz") if a more
994       specific handler isn't defined.  Be sure to quote any exception types
995       that contain periods to prevent Perl concatenating them into a single
996       string (i.e. "user.passwd" is parsed as 'user'.'passwd').
997
998           my $template = Template->new({
999               ERROR => {
1000                   'user.login'  => 'user/login.html',
1001                   'user.passwd' => 'user/badpasswd.html',
1002                   'user'        => 'user/index.html',
1003                   'default'     => 'error/default',
1004               },
1005           });
1006
1007       In this example, any template processed by the $template object, or
1008       other templates or code called from within, can raise a "user.login"
1009       exception and have the service redirect to the user/login.html
1010       template.  Similarly, a "user.passwd" exception has a specific handling
1011       template, user/badpasswd.html, while all other "user" or "user.*"
1012       exceptions cause a redirection to the user/index.html page.  All other
1013       exception types are handled by error/default.
1014
1015       Exceptions can be raised in a template using the "THROW" directive,
1016
1017           [% THROW user.login 'no user id: please login' %]
1018
1019       or by calling the throw() method on the current Template::Context
1020       object,
1021
1022           $context->throw('user.passwd', 'Incorrect Password');
1023           $context->throw('Incorrect Password');    # type 'undef'
1024
1025       or from Perl code by calling "die()" with a Template::Exception object,
1026
1027           die (Template::Exception->new('user.denied', 'Invalid User ID'));
1028
1029       or by simply calling die() with an error string.  This is automagically
1030       caught and converted to an  exception of '"undef"' type which can then
1031       be handled in the usual way.
1032
1033           die "I'm sorry Dave, I can't do that";
1034
1035       Note that the '"undef"' we're talking about here is a literal string
1036       rather than Perl's "undef" used to represent undefined values.
1037

Template Runtime Options

1039   EVAL_PERL
1040       This flag is used to indicate if "PERL" and/or "RAWPERL" blocks should
1041       be evaluated.  It is disabled by default and any "PERL" or "RAWPERL"
1042       blocks encountered will raise exceptions of type '"perl"' with the
1043       message '"EVAL_PERL not set"'.  Note however that any "RAWPERL" blocks
1044       should always contain valid Perl code, regardless of the "EVAL_PERL"
1045       flag.  The parser will fail to compile templates that contain invalid
1046       Perl code in "RAWPERL" blocks and will throw a '"file"' exception.
1047
1048       When using compiled templates (see "Caching and Compiling Options"),
1049       the "EVAL_PERL" has an affect when the template is compiled, and again
1050       when the templates is subsequently processed, possibly in a different
1051       context to the one that compiled it.
1052
1053       If the "EVAL_PERL" is set when a template is compiled, then all "PERL"
1054       and "RAWPERL" blocks will be included in the compiled template.  If the
1055       "EVAL_PERL" option isn't set, then Perl code will be generated which
1056       always throws a '"perl"' exception with the message '"EVAL_PERL not
1057       set"' whenever the compiled template code is run.
1058
1059       Thus, you must have "EVAL_PERL" set if you want your compiled templates
1060       to include "PERL" and "RAWPERL" blocks.
1061
1062       At some point in the future, using a different invocation of the
1063       Template Toolkit, you may come to process such a pre-compiled template.
1064       Assuming the "EVAL_PERL" option was set at the time the template was
1065       compiled, then the output of any "RAWPERL" blocks will be included in
1066       the compiled template and will get executed when the template is
1067       processed.  This will happen regardless of the runtime "EVAL_PERL"
1068       status.
1069
1070       Regular "PERL" blocks are a little more cautious, however.  If the
1071       "EVAL_PERL" flag isn't set for the current context, that is, the one
1072       which is trying to process it, then it will throw the familiar '"perl"'
1073       exception with the message, '"EVAL_PERL not set"'.
1074
1075       Thus you can compile templates to include "PERL" blocks, but optionally
1076       disable them when you process them later.  Note however that it is
1077       possible for a "PERL" block to contain a Perl ""BEGIN { # some code }""
1078       block which will always get run regardless of the runtime "EVAL_PERL"
1079       status.  Thus, if you set "EVAL_PERL" when compiling templates, it is
1080       assumed that you trust the templates to Do The Right Thing.  Otherwise
1081       you must accept the fact that there's no bulletproof way to prevent any
1082       included code from trampling around in the living room of the runtime
1083       environment, making a real nuisance of itself if it really wants to.
1084       If you don't like the idea of such uninvited guests causing a bother,
1085       then you can accept the default and keep "EVAL_PERL" disabled.
1086
1087   OUTPUT
1088       Default output location or handler.  This may be specified as one of: a
1089       file name (relative to "OUTPUT_PATH", if defined, or the current
1090       working directory if not specified absolutely); a file handle (e.g.
1091       "GLOB" or IO::Handle) opened for writing; a reference to a text string
1092       to which the output is appended (the string isn't cleared); a reference
1093       to a subroutine which is called, passing the output text as an
1094       argument; as a reference to an array, onto which the content will be
1095       "push()"ed; or as a reference to any object that supports the "print()"
1096       method.  This latter option includes the "Apache::Request" object which
1097       is passed as the argument to Apache/mod_perl handlers.
1098
1099       example 1 (file name):
1100
1101           my $template = Template->new({
1102               OUTPUT => "/tmp/foo",
1103           });
1104
1105       example 2 (text string):
1106
1107           my $output   = '';
1108           my $template = Template->new({
1109               OUTPUT => \$output,
1110           });
1111
1112       example 3 (file handle):
1113
1114           open (TOUT, "> $file") || die "$file: $!\n";
1115           my $template = Template->new({
1116               OUTPUT => \*TOUT,
1117           });
1118
1119       example 4 (subroutine):
1120
1121           sub output { my $out = shift; print "OUTPUT: $out" }
1122           my $template = Template->new({
1123               OUTPUT => \&output,
1124           });
1125
1126       example 5 (array reference):
1127
1128           my $template = Template->new({
1129               OUTPUT => \@output,
1130           })
1131
1132       example 6 (Apache/mod_perl handler):
1133
1134           sub handler {
1135               my $r = shift;
1136               my $t = Template->new({
1137                   OUTPUT => $r,
1138               });
1139               ...
1140           }
1141
1142       The default "OUTPUT" location be overridden by passing a third
1143       parameter to the Template process() method. This can be specified as
1144       any of the above argument types.
1145
1146           $t->process($file, $vars, "/tmp/foo");
1147           $t->process($file, $vars, \$output);
1148           $t->process($file, $vars, \*MYGLOB);
1149           $t->process($file, $vars, \@output);
1150           $t->process($file, $vars, $r);  # Apache::Request
1151           ...
1152
1153   OUTPUT_PATH
1154       The "OUTPUT_PATH" allows a directory to be specified into which output
1155       files should be written.  An output file can be specified by the
1156       "OUTPUT" option, or passed by name as the third parameter to the
1157       Template process() method.
1158
1159           my $template = Template->new({
1160               INCLUDE_PATH => "/tmp/src",
1161               OUTPUT_PATH  => "/tmp/dest",
1162           });
1163
1164           my $vars = {
1165               ...
1166           };
1167
1168           foreach my $file ('foo.html', 'bar.html') {
1169               $template->process($file, $vars, $file)
1170                   || die $template->error();
1171           }
1172
1173       This example will read the input files /tmp/src/foo.html and
1174       /tmp/src/bar.html and write the processed output to /tmp/dest/foo.html
1175       and /tmp/dest/bar.html, respectively.
1176
1177   STRICT
1178       By default the Template Toolkit will silently ignore the use of
1179       undefined variables (a bad design decision that I regret).
1180
1181       When the "STRICT" option is set, the use of any undefined variables or
1182       values will cause an exception to be throw.  The exception will have a
1183       "type" of "var.undefined" and a message of the form "undefined
1184       variable: xxx".
1185
1186           my $template = Template->new(
1187               STRICT => 1
1188           );
1189
1190   DEBUG
1191       The "DEBUG" option can be used to enable debugging within the various
1192       different modules that comprise the Template Toolkit.  The
1193       Template::Constants module defines a set of "DEBUG_XXXX" constants
1194       which can be combined using the logical OR operator, '"|"'.
1195
1196           use Template::Constants qw( :debug );
1197
1198           my $template = Template->new({
1199               DEBUG => DEBUG_PARSER | DEBUG_PROVIDER,
1200           });
1201
1202       For convenience, you can also provide a string containing a list of
1203       lower case debug options, separated by any non-word characters.
1204
1205           my $template = Template->new({
1206               DEBUG => 'parser, provider',
1207           });
1208
1209       The following "DEBUG_XXXX" flags can be used:
1210
1211       DEBUG_SERVICE
1212           Enables general debugging messages for the Template::Service
1213           module.
1214
1215       DEBUG_CONTEXT
1216           Enables general debugging messages for the Template::Context
1217           module.
1218
1219       DEBUG_PROVIDER
1220           Enables general debugging messages for the Template::Provider
1221           module.
1222
1223       DEBUG_PLUGINS
1224           Enables general debugging messages for the Template::Plugins
1225           module.
1226
1227       DEBUG_FILTERS
1228           Enables general debugging messages for the Template::Filters
1229           module.
1230
1231       DEBUG_PARSER
1232           This flag causes the Template::Parser to generate debugging
1233           messages that show the Perl code generated by parsing and compiling
1234           each template.
1235
1236       DEBUG_UNDEF
1237           This option causes the Template Toolkit to throw an '"undef"' error
1238           whenever it encounters an undefined variable value.
1239
1240       DEBUG_DIRS
1241           This option causes the Template Toolkit to generate comments
1242           indicating the source file, line and original text of each
1243           directive in the template.  These comments are embedded in the
1244           template output using the format defined in the "DEBUG_FORMAT"
1245           configuration item, or a simple default format if unspecified.
1246
1247           For example, the following template fragment:
1248
1249               Hello World
1250
1251           would generate this output:
1252
1253               ## input text line 1 :  ##
1254               Hello
1255               ## input text line 2 : World ##
1256               World
1257
1258       DEBUG_ALL
1259           Enables all debugging messages.
1260
1261       DEBUG_CALLER
1262           This option causes all debug messages that aren't newline
1263           terminated to have the file name and line number of the caller
1264           appended to them.
1265
1266   DEBUG_FORMAT
1267       The "DEBUG_FORMAT" option can be used to specify a format string for
1268       the debugging messages generated via the "DEBUG_DIRS" option described
1269       above.  Any occurrences of $file, $line or $text will be replaced with
1270       the current file name, line or directive text, respectively.  Notice
1271       how the format is single quoted to prevent Perl from interpolating
1272       those tokens as variables.
1273
1274           my $template = Template->new({
1275               DEBUG => 'dirs',
1276               DEBUG_FORMAT => '<!-- $file line $line : [% $text %] -->',
1277           });
1278
1279       The following template fragment:
1280
1281           [% foo = 'World' %]
1282           Hello [% foo %]
1283
1284       would then generate this output:
1285
1286           <!-- input text line 2 : [% foo = 'World' %] -->
1287           Hello <!-- input text line 3 : [% foo %] -->World
1288
1289       The DEBUG directive can also be used to set a debug format within a
1290       template.
1291
1292           [% DEBUG format '<!-- $file line $line : [% $text %] -->' %]
1293

Caching and Compiling Options

1295   CACHE_SIZE
1296       The Template::Provider module caches compiled templates to avoid the
1297       need to re-parse template files or blocks each time they are used. The
1298       "CACHE_SIZE" option is used to limit the number of compiled templates
1299       that the module should cache.
1300
1301       By default, the "CACHE_SIZE" is undefined and all compiled templates
1302       are cached.  When set to any positive value, the cache will be limited
1303       to storing no more than that number of compiled templates.  When a new
1304       template is loaded and compiled and the cache is full (i.e. the number
1305       of entries == "CACHE_SIZE"), the least recently used compiled template
1306       is discarded to make room for the new one.
1307
1308       The "CACHE_SIZE" can be set to 0 to disable caching altogether.
1309
1310           my $template = Template->new({
1311               CACHE_SIZE => 64,   # only cache 64 compiled templates
1312           });
1313
1314           my $template = Template->new({
1315               CACHE_SIZE => 0,   # don't cache any compiled templates
1316           });
1317
1318       As well as caching templates as they are found, the Template::Provider
1319       also implements negative caching to keep track of templates that are
1320       not found.  This allows the provider to quickly decline a request for a
1321       template that it has previously failed to locate, saving the effort of
1322       going to look for it again.  This is useful when an "INCLUDE_PATH"
1323       includes multiple providers, ensuring that the request is passed down
1324       through the providers as quickly as possible.
1325
1326   STAT_TTL
1327       This value can be set to control how long the Template::Provider will
1328       keep a template cached in memory before checking to see if the source
1329       template has changed.
1330
1331           my $provider = Template::Provider->new({
1332               STAT_TTL => 60,  # one minute
1333           });
1334
1335       The default value is 1 (second). You'll probably want to set this to a
1336       higher value if you're running the Template Toolkit inside a persistent
1337       web server application (e.g. mod_perl). For example, set it to 60 and
1338       the provider will only look for changes to templates once a minute at
1339       most. However, during development (or any time you're making frequent
1340       changes to templates) you'll probably want to keep it set to a low
1341       value so that you don't have to wait for the provider to notice that
1342       your templates have changed.
1343
1344   COMPILE_EXT
1345       From version 2 onwards, the Template Toolkit has the ability to compile
1346       templates to Perl code and save them to disk for subsequent use (i.e.
1347       cache persistence).  The "COMPILE_EXT" option may be provided to
1348       specify a filename extension for compiled template files.  It is
1349       undefined by default and no attempt will be made to read or write any
1350       compiled template files.
1351
1352           my $template = Template->new({
1353               COMPILE_EXT => '.ttc',
1354           });
1355
1356       If "COMPILE_EXT" is defined (and "COMPILE_DIR" isn't, see below) then
1357       compiled template files with the "COMPILE_EXT" extension will be
1358       written to the same directory from which the source template files were
1359       loaded.
1360
1361       Compiling and subsequent reuse of templates happens automatically
1362       whenever the "COMPILE_EXT" or "COMPILE_DIR" options are set.  The
1363       Template Toolkit will automatically reload and reuse compiled files
1364       when it finds them on disk.  If the corresponding source file has been
1365       modified since the compiled version as written, then it will load and
1366       re-compile the source and write a new compiled version to disk.
1367
1368       This form of cache persistence offers significant benefits in terms of
1369       time and resources required to reload templates.  Compiled templates
1370       can be reloaded by a simple call to Perl's "require()", leaving Perl to
1371       handle all the parsing and compilation.  This is a Good Thing.
1372
1373   COMPILE_DIR
1374       The "COMPILE_DIR" option is used to specify an alternate directory root
1375       under which compiled template files should be saved.
1376
1377           my $template = Template->new({
1378               COMPILE_DIR => '/tmp/ttc',
1379           });
1380
1381       The "COMPILE_EXT" option may also be specified to have a consistent
1382       file extension added to these files.
1383
1384           my $template1 = Template->new({
1385               COMPILE_DIR => '/tmp/ttc',
1386               COMPILE_EXT => '.ttc1',
1387           });
1388
1389           my $template2 = Template->new({
1390               COMPILE_DIR => '/tmp/ttc',
1391               COMPILE_EXT => '.ttc2',
1392           });
1393
1394       When "COMPILE_EXT" is undefined, the compiled template files have the
1395       same name as the original template files, but reside in a different
1396       directory tree.
1397
1398       Each directory in the "INCLUDE_PATH" is replicated in full beneath the
1399       "COMPILE_DIR" directory.  This example:
1400
1401           my $template = Template->new({
1402               COMPILE_DIR  => '/tmp/ttc',
1403               INCLUDE_PATH => '/home/abw/templates:/usr/share/templates',
1404           });
1405
1406       would create the following directory structure:
1407
1408           /tmp/ttc/home/abw/templates/
1409           /tmp/ttc/usr/share/templates/
1410
1411       Files loaded from different "INCLUDE_PATH" directories will have their
1412       compiled forms save in the relevant "COMPILE_DIR" directory.
1413
1414       On Win32 platforms a filename may by prefixed by a drive letter and
1415       colon.  e.g.
1416
1417           C:/My Templates/header
1418
1419       The colon will be silently stripped from the filename when it is added
1420       to the "COMPILE_DIR" value(s) to prevent illegal filename being
1421       generated.  Any colon in "COMPILE_DIR" elements will be left intact.
1422       For example:
1423
1424           # Win32 only
1425           my $template = Template->new({
1426               DELIMITER    => ';',
1427               COMPILE_DIR  => 'C:/TT2/Cache',
1428               INCLUDE_PATH => 'C:/TT2/Templates;D:/My Templates',
1429           });
1430
1431       This would create the following cache directories:
1432
1433           C:/TT2/Cache/C/TT2/Templates
1434           C:/TT2/Cache/D/My Templates
1435

Plugins and Filters

1437   PLUGINS
1438       The "PLUGINS" options can be used to provide a reference to a hash
1439       array that maps plugin names to Perl module names.  A number of
1440       standard plugins are defined (e.g. "table", "format", "cgi", etc.)
1441       which map to their corresponding "Template::Plugin::*" counterparts.
1442       These can be redefined by values in the "PLUGINS" hash.
1443
1444           my $template = Template->new({
1445               PLUGINS => {
1446                   cgi => 'MyOrg::Template::Plugin::CGI',
1447                   foo => 'MyOrg::Template::Plugin::Foo',
1448                   bar => 'MyOrg::Template::Plugin::Bar',
1449               },
1450           });
1451
1452       The recommended convention is to specify these plugin names in lower
1453       case.  The Template Toolkit first looks for an exact case-sensitive
1454       match and then tries the lower case conversion of the name specified.
1455
1456           [% USE Foo %]      # look for 'Foo' then 'foo'
1457
1458       If you define all your "PLUGINS" with lower case names then they will
1459       be located regardless of how the user specifies the name in the USE
1460       directive.  If, on the other hand, you define your "PLUGINS" with upper
1461       or mixed case names then the name specified in the "USE" directive must
1462       match the case exactly.
1463
1464       The "USE" directive is used to create plugin objects and does so by
1465       calling the plugin() method on the current Template::Context object. If
1466       the plugin name is defined in the "PLUGINS" hash then the corresponding
1467       Perl module is loaded via "require()". The context then calls the
1468       load() class method which should return the class name (default and
1469       general case) or a prototype object against which the new() method can
1470       be called to instantiate individual plugin objects.
1471
1472       If the plugin name is not defined in the "PLUGINS" hash then the
1473       "PLUGIN_BASE" and/or "LOAD_PERL" options come into effect.
1474
1475   PLUGIN_BASE
1476       If a plugin is not defined in the "PLUGINS" hash then the "PLUGIN_BASE"
1477       is used to attempt to construct a correct Perl module name which can be
1478       successfully loaded.
1479
1480       The "PLUGIN_BASE" can be specified as a reference to an array of module
1481       namespaces, or as a single value which is automatically converted to a
1482       list.  The default "PLUGIN_BASE" value ("Template::Plugin") is then
1483       added to the end of this list.
1484
1485       example 1:
1486
1487           my $template = Template->new({
1488               PLUGIN_BASE => 'MyOrg::Template::Plugin',
1489           });
1490
1491           [% USE Foo %]    # => MyOrg::Template::Plugin::Foo
1492                              or        Template::Plugin::Foo
1493
1494       example 2:
1495
1496           my $template = Template->new({
1497               PLUGIN_BASE => [   'MyOrg::Template::Plugin',
1498                                  'YourOrg::Template::Plugin'  ],
1499           });
1500
1501       template:
1502
1503           [% USE Foo %]    # =>   MyOrg::Template::Plugin::Foo
1504                              or YourOrg::Template::Plugin::Foo
1505                              or          Template::Plugin::Foo
1506
1507       If you don't want the default "Template::Plugin" namespace added to the
1508       end of the "PLUGIN_BASE", then set the $Template::Plugins::PLUGIN_BASE
1509       variable to a false value before calling the new() Template#new()
1510       constructor method.  This is shown in the example below where the "Foo"
1511       plugin is located as "My::Plugin::Foo" or "Your::Plugin::Foo" but not
1512       as "Template::Plugin::Foo".
1513
1514       example 3:
1515
1516           use Template::Plugins;
1517           $Template::Plugins::PLUGIN_BASE = '';
1518
1519           my $template = Template->new({
1520               PLUGIN_BASE => [   'My::Plugin',
1521                                  'Your::Plugin'  ],
1522           });
1523
1524       template:
1525
1526           [% USE Foo %]    # =>   My::Plugin::Foo
1527                              or Your::Plugin::Foo
1528
1529   LOAD_PERL
1530       If a plugin cannot be loaded using the "PLUGINS" or "PLUGIN_BASE"
1531       approaches then the provider can make a final attempt to load the
1532       module without prepending any prefix to the module path.  This allows
1533       regular Perl modules (i.e. those that don't reside in the
1534       Template::Plugin or some other such namespace) to be loaded and used as
1535       plugins.
1536
1537       By default, the "LOAD_PERL" option is set to 0 and no attempt will be
1538       made to load any Perl modules that aren't named explicitly in the
1539       "PLUGINS" hash or reside in a package as named by one of the
1540       "PLUGIN_BASE" components.
1541
1542       Plugins loaded using the "PLUGINS" or "PLUGIN_BASE" receive a reference
1543       to the current context object as the first argument to the new()
1544       constructor. Modules loaded using "LOAD_PERL" are assumed to not
1545       conform to the plugin interface. They must provide a "new()" class
1546       method for instantiating objects but it will not receive a reference to
1547       the context as the first argument.
1548
1549       Plugin modules should provide a load() class method (or inherit the
1550       default one from the Template::Plugin base class) which is called the
1551       first time the plugin is loaded. Regular Perl modules need not. In all
1552       other respects, regular Perl objects and Template Toolkit plugins are
1553       identical.
1554
1555       If a particular Perl module does not conform to the common, but not
1556       unilateral, "new()" constructor convention then a simple plugin wrapper
1557       can be written to interface to it.
1558
1559   FILTERS
1560       The "FILTERS" option can be used to specify custom filters which can
1561       then be used with the "FILTER" directive like any other.  These are
1562       added to the standard filters which are available by default.  Filters
1563       specified via this option will mask any standard filters of the same
1564       name.
1565
1566       The "FILTERS" option should be specified as a reference to a hash array
1567       in which each key represents the name of a filter.  The corresponding
1568       value should contain a reference to an array containing a subroutine
1569       reference and a flag which indicates if the filter is static (0) or
1570       dynamic (1).  A filter may also be specified as a solitary subroutine
1571       reference and is assumed to be static.
1572
1573           $template = Template->new({
1574               FILTERS => {
1575                   'sfilt1' =>   \&static_filter,      # static
1576                   'sfilt2' => [ \&static_filter, 0 ], # same as above
1577                   'dfilt1' => [ \&dyanamic_filter_factory, 1 ],
1578               },
1579           });
1580
1581       Additional filters can be specified at any time by calling the
1582       define_filter() method on the current Template::Context object. The
1583       method accepts a filter name, a reference to a filter subroutine and an
1584       optional flag to indicate if the filter is dynamic.
1585
1586           my $context = $template->context();
1587           $context->define_filter('new_html', \&new_html);
1588           $context->define_filter('new_repeat', \&new_repeat, 1);
1589
1590       Static filters are those where a single subroutine reference is used
1591       for all invocations of a particular filter.  Filters that don't accept
1592       any configuration parameters (e.g. "html") can be implemented
1593       statically.  The subroutine reference is simply returned when that
1594       particular filter is requested.  The subroutine is called to filter the
1595       output of a template block which is passed as the only argument.  The
1596       subroutine should return the modified text.
1597
1598           sub static_filter {
1599               my $text = shift;
1600               # do something to modify $text...
1601               return $text;
1602           }
1603
1604       The following template fragment:
1605
1606           [% FILTER sfilt1 %]
1607           Blah blah blah.
1608           [% END %]
1609
1610       is approximately equivalent to:
1611
1612           &static_filter("\nBlah blah blah.\n");
1613
1614       Filters that can accept parameters (e.g. "truncate") should be
1615       implemented dynamically.  In this case, the subroutine is taken to be a
1616       filter 'factory' that is called to create a unique filter subroutine
1617       each time one is requested.  A reference to the current
1618       Template::Context object is passed as the first parameter, followed by
1619       any additional parameters specified.  The subroutine should return
1620       another subroutine reference (usually a closure) which implements the
1621       filter.
1622
1623           sub dynamic_filter_factory {
1624               my ($context, @args) = @_;
1625
1626               return sub {
1627                   my $text = shift;
1628                   # do something to modify $text...
1629                   return $text;
1630               }
1631           }
1632
1633       The following template fragment:
1634
1635           [% FILTER dfilt1(123, 456) %]
1636           Blah blah blah
1637           [% END %]
1638
1639       is approximately equivalent to:
1640
1641           my $filter = &dynamic_filter_factory($context, 123, 456);
1642           &$filter("\nBlah blah blah.\n");
1643
1644       See the "FILTER" directive for further examples.
1645

Customisation and Extension

1647   LOAD_TEMPLATES
1648       The "LOAD_TEMPLATES" option can be used to provide a reference to a
1649       list of Template::Provider objects or sub-classes thereof which will
1650       take responsibility for loading and compiling templates.
1651
1652           my $template = Template->new({
1653               LOAD_TEMPLATES => [
1654                   MyOrg::Template::Provider->new({ ... }),
1655                   Template::Provider->new({ ... }),
1656               ],
1657           });
1658
1659       When a "PROCESS", "INCLUDE" or "WRAPPER" directive is encountered, the
1660       named template may refer to a locally defined "BLOCK" or a file
1661       relative to the "INCLUDE_PATH" (or an absolute or relative path if the
1662       appropriate "ABSOLUTE" or "RELATIVE" options are set). If a "BLOCK"
1663       definition can't be found (see the Template::Context template() method
1664       for a discussion of "BLOCK" locality) then each of the "LOAD_TEMPLATES"
1665       provider objects is queried in turn via the fetch() method to see if it
1666       can supply the required template.
1667
1668       Each provider can return a compiled template, an error, or decline to
1669       service the request in which case the responsibility is passed to the
1670       next provider.  If none of the providers can service the request then a
1671       'not found' error is returned. The same basic provider mechanism is
1672       also used for the "INSERT" directive but it bypasses any "BLOCK"
1673       definitions and doesn't attempt is to parse or process the contents of
1674       the template file.
1675
1676       If "LOAD_TEMPLATES" is undefined, a single default provider will be
1677       instantiated using the current configuration parameters. For example,
1678       the Template::Provider "INCLUDE_PATH" option can be specified in the
1679       Template configuration and will be correctly passed to the provider's
1680       constructor method.
1681
1682           my $template = Template->new({
1683               INCLUDE_PATH => '/here:/there',
1684           });
1685
1686   LOAD_PLUGINS
1687       The "LOAD_PLUGINS" options can be used to specify a list of provider
1688       objects (i.e. they implement the fetch() method) which are responsible
1689       for loading and instantiating template plugin objects. The
1690       Template::Context plugin() method queries each provider in turn in a
1691       "Chain of Responsibility" as per the template() and filter() methods.
1692
1693           my $template = Template->new({
1694               LOAD_PLUGINS => [
1695                   MyOrg::Template::Plugins->new({ ... }),
1696                   Template::Plugins->new({ ... }),
1697               ],
1698           });
1699
1700       By default, a single Template::Plugins object is created using the
1701       current configuration hash.  Configuration items destined for the
1702       Template::Plugins constructor may be added to the Template constructor.
1703
1704           my $template = Template->new({
1705               PLUGIN_BASE => 'MyOrg::Template::Plugins',
1706               LOAD_PERL   => 1,
1707           });
1708
1709   LOAD_FILTERS
1710       The "LOAD_FILTERS" option can be used to specify a list of provider
1711       objects (i.e. they implement the fetch() method) which are responsible
1712       for returning and/or creating filter subroutines. The Template::Context
1713       filter() method queries each provider in turn in a "Chain of
1714       Responsibility" as per the template() and plugin() methods.
1715
1716           my $template = Template->new({
1717               LOAD_FILTERS => [
1718                   MyTemplate::Filters->new(),
1719                   Template::Filters->new(),
1720               ],
1721           });
1722
1723       By default, a single Template::Filters object is created for the
1724       "LOAD_FILTERS" list.
1725
1726   TOLERANT
1727       The "TOLERANT" flag is used by the various Template Toolkit provider
1728       modules (Template::Provider, Template::Plugins, Template::Filters) to
1729       control their behaviour when errors are encountered. By default, any
1730       errors are reported as such, with the request for the particular
1731       resource ("template", "plugin", "filter") being denied and an exception
1732       raised.
1733
1734       When the "TOLERANT" flag is set to any true values, errors will be
1735       silently ignored and the provider will instead return
1736       "STATUS_DECLINED". This allows a subsequent provider to take
1737       responsibility for providing the resource, rather than failing the
1738       request outright. If all providers decline to service the request,
1739       either through tolerated failure or a genuine disinclination to comply,
1740       then a '"<resource> not found"' exception is raised.
1741
1742   SERVICE
1743       A reference to a Template::Service object, or sub-class thereof, to
1744       which the Template module should delegate.  If unspecified, a
1745       Template::Service object is automatically created using the current
1746       configuration hash.
1747
1748           my $template = Template->new({
1749               SERVICE => MyOrg::Template::Service->new({ ... }),
1750           });
1751
1752   CONTEXT
1753       A reference to a Template::Context object which is used to define a
1754       specific environment in which template are processed. A
1755       Template::Context object is passed as the only parameter to the Perl
1756       subroutines that represent "compiled" template documents. Template
1757       subroutines make callbacks into the context object to access Template
1758       Toolkit functionality, for example, to "INCLUDE" or "PROCESS" another
1759       template (include() and process() methods, respectively), to "USE" a
1760       plugin (plugin()) or instantiate a filter (filter()) or to access the
1761       stash (stash()) which manages variable definitions via the get() and
1762       set() methods.
1763
1764           my $template = Template->new({
1765               CONTEXT => MyOrg::Template::Context->new({ ... }),
1766           });
1767
1768   STASH
1769       A reference to a Template::Stash object or sub-class which will take
1770       responsibility for managing template variables.
1771
1772           my $stash = MyOrg::Template::Stash->new({ ... });
1773           my $template = Template->new({
1774               STASH => $stash,
1775           });
1776
1777       If unspecified, a default stash object is created using the "VARIABLES"
1778       configuration item to initialise the stash variables.
1779
1780           my $template = Template->new({
1781               VARIABLES => {
1782                   id    => 'abw',
1783                   name  => 'Andy Wardley',
1784               },
1785           };
1786
1787   PARSER
1788       The Template::Parser module implements a parser object for compiling
1789       templates into Perl code which can then be executed.  A default object
1790       of this class is created automatically and then used by the
1791       Template::Provider whenever a template is loaded and requires
1792       compilation.  The "PARSER" option can be used to provide a reference to
1793       an alternate parser object.
1794
1795           my $template = Template->new({
1796               PARSER => MyOrg::Template::Parser->new({ ... }),
1797           });
1798
1799   GRAMMAR
1800       The "GRAMMAR" configuration item can be used to specify an alternate
1801       grammar for the parser.  This allows a modified or entirely new
1802       template language to be constructed and used by the Template Toolkit.
1803
1804       Source templates are compiled to Perl code by the Template::Parser
1805       using the Template::Grammar (by default) to define the language
1806       structure and semantics.  Compiled templates are thus inherently
1807       "compatible" with each other and there is nothing to prevent any number
1808       of different template languages being compiled and used within the same
1809       Template Toolkit processing environment (other than the usual time and
1810       memory constraints).
1811
1812       The Template::Grammar file is constructed from a YACC like grammar
1813       (using "Parse::YAPP") and a skeleton module template.  These files are
1814       provided, along with a small script to rebuild the grammar, in the
1815       parser sub-directory of the distribution.
1816
1817       You don't have to know or worry about these unless you want to hack on
1818       the template language or define your own variant. There is a README
1819       file in the same directory which provides some small guidance but it is
1820       assumed that you know what you're doing if you venture herein. If you
1821       grok LALR parsers, then you should find it comfortably familiar.
1822
1823       By default, an instance of the default Template::Grammar will be
1824       created and used automatically if a "GRAMMAR" item isn't specified.
1825
1826           use MyOrg::Template::Grammar;
1827
1828           my $template = Template->new({
1829               GRAMMAR = MyOrg::Template::Grammar->new();
1830           });
1831
1832
1833
1834perl v5.30.0                      2019-07-26       Template::Manual::Config(3)
Impressum