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

Template Files and Blocks

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

Template Variables

499   VARIABLES
500       The "VARIABLES" option (or "PRE_DEFINE" - they're equivalent) can be
501       used to specify a hash array of template variables that should be used
502       to pre-initialise the stash when it is created.  These items are
503       ignored if the "STASH" item is defined.
504
505           my $template = Template->new({
506               VARIABLES => {
507                   title   => 'A Demo Page',
508                   author  => 'Joe Random Hacker',
509                   version => 3.14,
510               },
511           };
512
513       or
514
515           my $template = Template->new({
516               PRE_DEFINE => {
517                   title   => 'A Demo Page',
518                   author  => 'Joe Random Hacker',
519                   version => 3.14,
520               },
521           };
522
523   CONSTANTS
524       The "CONSTANTS" option can be used to specify a hash array of template
525       variables that are compile-time constants.  These variables are
526       resolved once when the template is compiled, and thus don't require
527       further resolution at runtime.  This results in significantly faster
528       processing of the compiled templates and can be used for variables that
529       don't change from one request to the next.
530
531           my $template = Template->new({
532               CONSTANTS => {
533                   title   => 'A Demo Page',
534                   author  => 'Joe Random Hacker',
535                   version => 3.14,
536               },
537           };
538
539   CONSTANT_NAMESPACE
540       Constant variables are accessed via the "constants" namespace by
541       default.
542
543           [% constants.title %]
544
545       The "CONSTANTS_NAMESPACE" option can be set to specify an alternate
546       namespace.
547
548           my $template = Template->new({
549               CONSTANTS => {
550                   title   => 'A Demo Page',
551                   # ...etc...
552               },
553               CONSTANTS_NAMESPACE => 'const',
554           };
555
556       In this case the constants would then be accessed as:
557
558           [% const.title %]
559
560   NAMESPACE
561       The constant folding mechanism described above is an example of a
562       namespace handler.  Namespace handlers can be defined to provide
563       alternate parsing mechanisms for variables in different namespaces.
564
565       Under the hood, the Template module converts a constructor
566       configuration such as:
567
568           my $template = Template->new({
569               CONSTANTS => {
570                   title   => 'A Demo Page',
571                   # ...etc...
572               },
573               CONSTANTS_NAMESPACE => 'const',
574           };
575
576       into one like:
577
578           my $template = Template->new({
579               NAMESPACE => {
580                   const => Template:::Namespace::Constants->new({
581                       title   => 'A Demo Page',
582                       # ...etc...
583                   }),
584               },
585           };
586
587       You can use this mechanism to define multiple constant namespaces, or
588       to install custom handlers of your own.
589
590           my $template = Template->new({
591               NAMESPACE => {
592                   site => Template:::Namespace::Constants->new({
593                       title   => "Wardley's Widgets",
594                       version => 2.718,
595                   }),
596                   author => Template:::Namespace::Constants->new({
597                       name  => 'Andy Wardley',
598                       email => 'abw@andywardley.com',
599                   }),
600                   voodoo => My::Namespace::Handler->new( ... ),
601               },
602           };
603
604       Now you have two constant namespaces, for example:
605
606           [% site.title %]
607           [% author.name %]
608
609       as well as your own custom namespace handler installed for the 'voodoo'
610       namespace.
611
612           [% voodoo.magic %]
613
614       See Template::Namespace::Constants for an example of what a namespace
615       handler looks like on the inside.
616

Template Processing Options

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

Template Runtime Options

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

Caching and Compiling Options

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

Plugins and Filters

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

Customisation and Extension

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