1Template::Manual::ConfiUgs(e3r)Contributed Perl DocumentTaetmipolnate::Manual::Config(3)
2
3
4
6 Template::Manual::Config - Configuration options
7
9 Template Style and Parsing Options
10
11 START_TAG, END_TAG
12 The START_TAG and END_TAG options are used to specify character
13 sequences or regular expressions that mark the start and end of a
14 template directive. The default values for START_TAG and END_TAG
15 are '[%' and '%]' respectively, giving us the familiar directive
16 style:
17
18 [% example %]
19
20 Any Perl regex characters can be used and therefore should be
21 escaped (or use the Perl "quotemeta" function) if they are intended
22 to represent literal characters.
23
24 my $template = Template->new({
25 START_TAG => quotemeta('<+'),
26 END_TAG => quotemeta('+>'),
27 });
28
29 example:
30
31 <+ INCLUDE foobar +>
32
33 The TAGS directive can also be used to set the START_TAG and
34 END_TAG values on a per-template file basis.
35
36 [% TAGS <+ +> %]
37
38 TAG_STYLE
39 The TAG_STYLE option can be used to set both START_TAG and END_TAG
40 according to pre-defined tag styles.
41
42 my $template = Template->new({
43 TAG_STYLE => 'star',
44 });
45
46 Available styles are:
47
48 template [% ... %] (default)
49 template1 [% ... %] or %% ... %% (TT version 1)
50 metatext %% ... %% (Text::MetaText)
51 star [* ... *] (TT alternate)
52 php <? ... ?> (PHP)
53 asp <% ... %> (ASP)
54 mason <% ... > (HTML::Mason)
55 html <!-- ... --> (HTML comments)
56
57 Any values specified for START_TAG and/or END_TAG will over-ride
58 those defined by a TAG_STYLE.
59
60 The TAGS directive may also be used to set a TAG_STYLE
61
62 [% TAGS html %]
63 <!-- INCLUDE header -->
64
65 PRE_CHOMP, POST_CHOMP
66 Anything outside a directive tag is considered plain text and is
67 generally passed through unaltered (but see the INTERPOLATE
68 option). This includes all whitespace and newlines characters sur‐
69 rounding directive tags. Directives that don't generate any output
70 will leave gaps in the output document.
71
72 Example:
73
74 Foo
75 [% a = 10 %]
76 Bar
77
78 Output:
79
80 Foo
81
82 Bar
83
84 The PRE_CHOMP and POST_CHOMP options can help to clean up some of
85 this extraneous whitespace. Both are disabled by default.
86
87 my $template = Template-E<gt>new({
88 PRE_CHOMP =E<gt> 1,
89 POST_CHOMP =E<gt> 1,
90 });
91
92 With PRE_CHOMP set to 1, the newline and whitespace preceding a
93 directive at the start of a line will be deleted. This has the
94 effect of concatenating a line that starts with a directive onto
95 the end of the previous line.
96
97 Foo E<lt>----------.
98 ⎪
99 ,---(PRE_CHOMP)----'
100 ⎪
101 `-- [% a = 10 %] --.
102 ⎪
103 ,---(POST_CHOMP)---'
104 ⎪
105 `-E<gt> Bar
106
107 With POST_CHOMP set to 1, any whitespace after a directive up to
108 and including the newline will be deleted. This has the effect of
109 joining a line that ends with a directive onto the start of the
110 next line.
111
112 If PRE_CHOMP or POST_CHOMP is set to 2, all whitespace including
113 any number of newline will be removed and replaced with a single
114 space. This is useful for HTML, where (usually) a contiguous block
115 of whitespace is rendered the same as a single space.
116
117 With PRE_CHOMP or POST_CHOMP set to 3, all adjacent whitespace
118 (including newlines) will be removed entirely.
119
120 These values are defined as CHOMP_NONE, CHOMP_ONE, CHOMP_COLLAPSE
121 and CHOMP_GREEDY constants in the Template::Constants module.
122 CHOMP_ALL is also defined as an alias for CHOMP_ONE to provide
123 backwards compatability with earlier version of the Template Tool‐
124 kit.
125
126 Additionally the chomp tag modifiers listed below may also be used
127 for the PRE_CHOMP and POST_CHOMP configuration.
128
129 my $template = Template-E<gt>new({
130 PRE_CHOMP =E<lt> '~',
131 POST_CHOMP =E<gt> '-',
132 });
133
134 PRE_CHOMP and POST_CHOMP can be activated for individual directives
135 by placing a '-' immediately at the start and/or end of the direc‐
136 tive.
137
138 [% FOREACH user IN userlist %]
139 [%- user -%]
140 [% END %]
141
142 This has the same effect as CHOMP_ONE in removing all whitespace
143 before or after the directive up to and including the newline. The
144 template will be processed as if written:
145
146 [% FOREACH user IN userlist %][% user %][% END %]
147
148 To remove all whitespace including any number of newlines, use the
149 '~' character instead.
150
151 [% FOREACH user IN userlist %]
152
153 [%~ user ~%]
154
155 [% END %]
156
157 To collapse all whitespace to a single space, use the '=' charac‐
158 ter.
159
160 [% FOREACH user IN userlist %]
161
162 [%= user =%]
163
164 [% END %]
165
166 Here the template is processed as if written:
167
168 [% FOREACH user IN userlist %] [% user %] [% END %]
169
170 If you have PRE_CHOMP or POST_CHOMP set as configuration options
171 then you can use '+' to disable any chomping options (i.e. leave
172 the whitespace intact) on a per-directive basis.
173
174 [% FOREACH user = userlist %]
175 User: [% user +%]
176 [% END %]
177
178 With POST_CHOMP set to CHOMP_ONE, the above example would be parsed
179 as if written:
180
181 [% FOREACH user = userlist %]User: [% user %]
182 [% END %]
183
184 For reference, the PRE_CHOMP and POST_CHOMP configuration options
185 may be set to any of the following:
186
187 Constant Value Tag Modifier
188 ----------------------------------
189 CHOMP_NONE 0 +
190 CHOMP_ONE 1 -
191 CHOMP_COLLAPSE 2 =
192 CHOMP_GREEDY 3 ~
193
194 TRIM
195 The TRIM option can be set to have any leading and trailing white‐
196 space automatically removed from the output of all template files
197 and BLOCKs.
198
199 By example, the following BLOCK definition
200
201 [% BLOCK foo %]
202 Line 1 of foo
203 [% END %]
204
205 will be processed is as "\nLine 1 of foo\n". When INCLUDEd, the
206 surrounding newlines will also be introduced.
207
208 before
209 [% INCLUDE foo %]
210 after
211
212 output:
213 before
214
215 Line 1 of foo
216
217 after
218
219 With the TRIM option set to any true value, the leading and trail‐
220 ing newlines (which count as whitespace) will be removed from the
221 output of the BLOCK.
222
223 before
224 Line 1 of foo
225 after
226
227 The TRIM option is disabled (0) by default.
228
229 INTERPOLATE
230 The INTERPOLATE flag, when set to any true value will cause vari‐
231 able references in plain text (i.e. not surrounded by START_TAG and
232 END_TAG) to be recognised and interpolated accordingly.
233
234 my $template = Template->new({
235 INTERPOLATE => 1,
236 });
237
238 Variables should be prefixed by a '$' to identify them. Curly
239 braces can be used in the familiar Perl/shell style to explicitly
240 scope the variable name where required.
241
242 # INTERPOLATE => 0
243 <a href="http://[% server %]/[% help %]">
244 <img src="[% images %]/help.gif"></a>
245 [% myorg.name %]
246
247 # INTERPOLATE => 1
248 <a href="http://$server/$help">
249 <img src="$images/help.gif"></a>
250 $myorg.name
251
252 # explicit scoping with { }
253 <img src="$images/${icon.next}.gif">
254
255 Note that a limitation in Perl's regex engine restricts the maximum
256 length of an interpolated template to around 32 kilobytes or possi‐
257 bly less. Files that exceed this limit in size will typically
258 cause Perl to dump core with a segmentation fault. If you rou‐
259 tinely process templates of this size then you should disable
260 INTERPOLATE or split the templates in several smaller files or
261 blocks which can then be joined backed together via PROCESS or
262 INCLUDE.
263
264 ANYCASE
265 By default, directive keywords should be expressed in UPPER CASE.
266 The ANYCASE option can be set to allow directive keywords to be
267 specified in any case.
268
269 # ANYCASE => 0 (default)
270 [% INCLUDE foobar %] # OK
271 [% include foobar %] # ERROR
272 [% include = 10 %] # OK, 'include' is a variable
273
274 # ANYCASE => 1
275 [% INCLUDE foobar %] # OK
276 [% include foobar %] # OK
277 [% include = 10 %] # ERROR, 'include' is reserved word
278
279 One side-effect of enabling ANYCASE is that you cannot use a vari‐
280 able of the same name as a reserved word, regardless of case. The
281 reserved words are currently:
282
283 GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER
284 IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
285 USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
286 TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP
287 CLEAR TO STEP AND OR NOT MOD DIV END
288
289 The only lower case reserved words that cannot be used for vari‐
290 ables, regardless of the ANYCASE option, are the operators:
291
292 and or not mod div
293
294 Template Files and Blocks
295
296 INCLUDE_PATH
297 The INCLUDE_PATH is used to specify one or more directories in
298 which template files are located. When a template is requested
299 that isn't defined locally as a BLOCK, each of the INCLUDE_PATH
300 directories is searched in turn to locate the template file. Mul‐
301 tiple directories can be specified as a reference to a list or as a
302 single string where each directory is delimited by ':'.
303
304 my $template = Template->new({
305 INCLUDE_PATH => '/usr/local/templates',
306 });
307
308 my $template = Template->new({
309 INCLUDE_PATH => '/usr/local/templates:/tmp/my/templates',
310 });
311
312 my $template = Template->new({
313 INCLUDE_PATH => [ '/usr/local/templates',
314 '/tmp/my/templates' ],
315 });
316
317 On Win32 systems, a little extra magic is invoked, ignoring delim‐
318 iters that have ':' followed by a '/' or '\'. This avoids confu‐
319 sion when using directory names like 'C:\Blah Blah'.
320
321 When specified as a list, the INCLUDE_PATH path can contain ele‐
322 ments which dynamically generate a list of INCLUDE_PATH directo‐
323 ries. These generator elements can be specified as a reference to
324 a subroutine or an object which implements a paths() method.
325
326 my $template = Template->new({
327 INCLUDE_PATH => [ '/usr/local/templates',
328 \&incpath_generator,
329 My::IncPath::Generator->new( ... ) ],
330 });
331
332 Each time a template is requested and the INCLUDE_PATH examined,
333 the subroutine or object method will be called. A reference to a
334 list of directories should be returned. Generator subroutines
335 should report errors using die(). Generator objects should return
336 undef and make an error available via its error() method.
337
338 For example:
339
340 sub incpath_generator {
341
342 # ...some code...
343
344 if ($all_is_well) {
345 return \@list_of_directories;
346 }
347 else {
348 die "cannot generate INCLUDE_PATH...\n";
349 }
350 }
351
352 or:
353
354 package My::IncPath::Generator;
355
356 # Template::Base (or Class::Base) provides error() method
357 use Template::Base;
358 use base qw( Template::Base );
359
360 sub paths {
361 my $self = shift;
362
363 # ...some code...
364
365 if ($all_is_well) {
366 return \@list_of_directories;
367 }
368 else {
369 return $self->error("cannot generate INCLUDE_PATH...\n");
370 }
371 }
372
373 1;
374
375 DELIMITER
376 Used to provide an alternative delimiter character sequence for
377 separating paths specified in the INCLUDE_PATH. The default value
378 for DELIMITER is ':'.
379
380 # tolerate Silly Billy's file system conventions
381 my $template = Template->new({
382 DELIMITER => '; ',
383 INCLUDE_PATH => 'C:/HERE/NOW; D:/THERE/THEN',
384 });
385
386 # better solution: install Linux! :-)
387
388 On Win32 systems, the default delimiter is a little more intelli‐
389 gent, splitting paths only on ':' characters that aren't followed
390 by a '/'. This means that the following should work as planned,
391 splitting the INCLUDE_PATH into 2 separate directories, C:/foo and
392 C:/bar.
393
394 # on Win32 only
395 my $template = Template->new({
396 INCLUDE_PATH => 'C:/Foo:C:/Bar'
397 });
398
399 However, if you're using Win32 then it's recommended that you
400 explicitly set the DELIMITER character to something else (e.g. ';')
401 rather than rely on this subtle magic.
402
403 ABSOLUTE
404 The ABSOLUTE flag is used to indicate if templates specified with
405 absolute filenames (e.g. '/foo/bar') should be processed. It is
406 disabled by default and any attempt to load a template by such a
407 name will cause a 'file' exception to be raised.
408
409 my $template = Template->new({
410 ABSOLUTE => 1,
411 });
412
413 # this is why it's disabled by default
414 [% INSERT /etc/passwd %]
415
416 On Win32 systems, the regular expression for matching absolute
417 pathnames is tweaked slightly to also detect filenames that start
418 with a driver letter and colon, such as:
419
420 C:/Foo/Bar
421
422 RELATIVE
423 The RELATIVE flag is used to indicate if templates specified with
424 filenames relative to the current directory (e.g. './foo/bar' or
425 '../../some/where/else') should be loaded. It is also disabled by
426 default, and will raise a 'file' error if such template names are
427 encountered.
428
429 my $template = Template->new({
430 RELATIVE => 1,
431 });
432
433 [% INCLUDE ../logs/error.log %]
434
435 DEFAULT
436 The DEFAULT option can be used to specify a default template which
437 should be used whenever a specified template can't be found in the
438 INCLUDE_PATH.
439
440 my $template = Template->new({
441 DEFAULT => 'notfound.html',
442 });
443
444 If a non-existant template is requested through the Template
445 process() method, or by an INCLUDE, PROCESS or WRAPPER directive,
446 then the DEFAULT template will instead be processed, if defined.
447 Note that the DEFAULT template is not used when templates are spec‐
448 ified with absolute or relative filenames, or as a reference to a
449 input file handle or text string.
450
451 BLOCKS
452 The BLOCKS option can be used to pre-define a default set of tem‐
453 plate blocks. These should be specified as a reference to a hash
454 array mapping template names to template text, subroutines or Tem‐
455 plate::Document objects.
456
457 my $template = Template->new({
458 BLOCKS => {
459 header => 'The Header. [% title %]',
460 footer => sub { return $some_output_text },
461 another => Template::Document->new({ ... }),
462 },
463 });
464
465 AUTO_RESET
466 The AUTO_RESET option is set by default and causes the local BLOCKS
467 cache for the Template::Context object to be reset on each call to
468 the Template process() method. This ensures that any BLOCKs
469 defined within a template will only persist until that template is
470 finished processing. This prevents BLOCKs defined in one process‐
471 ing request from interfering with other independent requests subse‐
472 quently processed by the same context object.
473
474 The BLOCKS item may be used to specify a default set of block defi‐
475 nitions for the Template::Context object. Subsequent BLOCK defini‐
476 tions in templates will over-ride these but they will be reinstated
477 on each reset if AUTO_RESET is enabled (default), or if the Tem‐
478 plate::Context reset() method is called.
479
480 RECURSION
481 The template processor will raise a file exception if it detects
482 direct or indirect recursion into a template. Setting this option
483 to any true value will allow templates to include each other recur‐
484 sively.
485
486 Template Variables
487
488 VARIABLES, PRE_DEFINE
489 The VARIABLES option (or PRE_DEFINE - they're equivalent) can be
490 used to specify a hash array of template variables that should be
491 used to pre-initialise the stash when it is created. These items
492 are ignored if the STASH item is defined.
493
494 my $template = Template->new({
495 VARIABLES => {
496 title => 'A Demo Page',
497 author => 'Joe Random Hacker',
498 version => 3.14,
499 },
500 };
501
502 or
503
504 my $template = Template->new({
505 PRE_DEFINE => {
506 title => 'A Demo Page',
507 author => 'Joe Random Hacker',
508 version => 3.14,
509 },
510 };
511
512 CONSTANTS
513 The CONSTANTS option can be used to specify a hash array of tem‐
514 plate variables that are compile-time constants. These variables
515 are resolved once when the template is compiled, and thus don't
516 require further resolution at runtime. This results in signifi‐
517 cantly faster processing of the compiled templates and can be used
518 for variables that don't change from one request to the next.
519
520 my $template = Template->new({
521 CONSTANTS => {
522 title => 'A Demo Page',
523 author => 'Joe Random Hacker',
524 version => 3.14,
525 },
526 };
527
528 CONSTANT_NAMESPACE
529 Constant variables are accessed via the 'constants' namespace by
530 default.
531
532 [% constants.title %]
533
534 The CONSTANTS_NAMESPACE option can be set to specify an alternate
535 namespace.
536
537 my $template = Template->new({
538 CONSTANTS => {
539 title => 'A Demo Page',
540 # ...etc...
541 },
542 CONSTANTS_NAMESPACE => 'const',
543 };
544
545 In this case the constants would then be accessed as:
546
547 [% const.title %]
548
549 NAMESPACE
550 The constant folding mechanism described above is an example of a
551 namespace handler. Namespace handlers can be defined to provide
552 alternate parsing mechanisms for variables in different namespaces.
553
554 Under the hood, the Template module converts a constructor configu‐
555 ration such as:
556
557 my $template = Template->new({
558 CONSTANTS => {
559 title => 'A Demo Page',
560 # ...etc...
561 },
562 CONSTANTS_NAMESPACE => 'const',
563 };
564
565 into one like:
566
567 my $template = Template->new({
568 NAMESPACE => {
569 const => Template:::Namespace::Constants->new({
570 title => 'A Demo Page',
571 # ...etc...
572 }),
573 },
574 };
575
576 You can use this mechanism to define multiple constant namespaces,
577 or to install custom handlers of your own.
578
579 my $template = Template->new({
580 NAMESPACE => {
581 site => Template:::Namespace::Constants->new({
582 title => "Wardley's Widgets",
583 version => 2.718,
584 }),
585 author => Template:::Namespace::Constants->new({
586 name => 'Andy Wardley',
587 email => 'abw@andywardley.com',
588 }),
589 voodoo => My::Namespace::Handler->new( ... ),
590 },
591 };
592
593 Now you have 2 constant namespaces, for example:
594
595 [% site.title %]
596 [% author.name %]
597
598 as well as your own custom namespace handler installed for the
599 'voodoo' namespace.
600
601 [% voodoo.magic %]
602
603 See Template::Namespace::Constants for an example of what a names‐
604 pace handler looks like on the inside.
605
606 Template Processing Options
607
608 The following options are used to specify any additional templates that
609 should be processed before, after, around or instead of the template
610 passed as the first argument to the Template process() method. These
611 options can be perform various useful tasks such as adding standard
612 headers or footers to all pages, wrapping page output in other tem‐
613 plates, pre-defining variables or performing initialisation or cleanup
614 tasks, automatically generating page summary information, navigation
615 elements, and so on.
616
617 The task of processing the template is delegated internally to the Tem‐
618 plate::Service module which, unsurprisingly, also has a process()
619 method. Any templates defined by the PRE_PROCESS option are processed
620 first and any output generated is added to the output buffer. Then the
621 main template is processed, or if one or more PROCESS templates are
622 defined then they are instead processed in turn. In this case, one of
623 the PROCESS templates is responsible for processing the main template,
624 by a directive such as:
625
626 [% PROCESS $template %]
627
628 The output of processing the main template or the PROCESS template(s)
629 is then wrapped in any WRAPPER templates, if defined. WRAPPER tem‐
630 plates don't need to worry about explicitly processing the template
631 because it will have been done for them already. Instead WRAPPER tem‐
632 plates access the content they are wrapping via the 'content' variable.
633
634 wrapper before
635 [% content %]
636 wrapper after
637
638 This output generated from processing the main template, and/or any
639 PROCESS or WRAPPER templates is added to the output buffer. Finally,
640 any POST_PROCESS templates are processed and their output is also added
641 to the output buffer which is then returned.
642
643 If the main template throws an exception during processing then any
644 relevant template(s) defined via the ERROR option will be processed
645 instead. If defined and successfully processed, the output from the
646 error template will be added to the output buffer in place of the tem‐
647 plate that generated the error and processing will continue, applying
648 any WRAPPER and POST_PROCESS templates. If no relevant ERROR option is
649 defined, or if the error occurs in one of the PRE_PROCESS, WRAPPER or
650 POST_PROCESS templates, then the process will terminate immediately and
651 the error will be returned.
652
653 PRE_PROCESS, POST_PROCESS
654 These values may be set to contain the name(s) of template files
655 (relative to INCLUDE_PATH) which should be processed immediately
656 before and/or after each template. These do not get added to tem‐
657 plates processed into a document via directives such as INCLUDE,
658 PROCESS, WRAPPER etc.
659
660 my $template = Template->new({
661 PRE_PROCESS => 'header',
662 POST_PROCESS => 'footer',
663 };
664
665 Multiple templates may be specified as a reference to a list. Each
666 is processed in the order defined.
667
668 my $template = Template->new({
669 PRE_PROCESS => [ 'config', 'header' ],
670 POST_PROCESS => 'footer',
671 };
672
673 Alternately, multiple template may be specified as a single string,
674 delimited by ':'. This delimiter string can be changed via the
675 DELIMITER option.
676
677 my $template = Template->new({
678 PRE_PROCESS => 'config:header',
679 POST_PROCESS => 'footer',
680 };
681
682 The PRE_PROCESS and POST_PROCESS templates are evaluated in the
683 same variable context as the main document and may define or update
684 variables for subsequent use.
685
686 config:
687
688 [% # set some site-wide variables
689 bgcolor = '#ffffff'
690 version = 2.718
691 %]
692
693 header:
694
695 [% DEFAULT title = 'My Funky Web Site' %]
696 <html>
697 <head>
698 <title>[% title %]</title>
699 </head>
700 <body bgcolor="[% bgcolor %]">
701
702 footer:
703
704 <hr>
705 Version [% version %]
706 </body>
707 </html>
708
709 The Template::Document object representing the main template being
710 processed is available within PRE_PROCESS and POST_PROCESS tem‐
711 plates as the 'template' variable. Metadata items defined via the
712 META directive may be accessed accordingly.
713
714 $template->process('mydoc.html', $vars);
715
716 mydoc.html:
717
718 [% META title = 'My Document Title' %]
719 blah blah blah
720 ...
721
722 header:
723
724 <html>
725 <head>
726 <title>[% template.title %]</title></head>
727 <body bgcolor="[% bgcolor %]">
728
729 PROCESS
730 The PROCESS option may be set to contain the name(s) of template
731 files (relative to INCLUDE_PATH) which should be processed instead
732 of the main template passed to the Template process() method. This
733 can be used to apply consistent wrappers around all templates, sim‐
734 ilar to the use of PRE_PROCESS and POST_PROCESS templates.
735
736 my $template = Template->new({
737 PROCESS => 'content',
738 };
739
740 # processes 'content' instead of 'foo.html'
741 $template->process('foo.html');
742
743 A reference to the original template is available in the 'template'
744 variable. Metadata items can be inspected and the template can be
745 processed by specifying it as a variable reference (i.e. prefixed
746 by '$') to an INCLUDE, PROCESS or WRAPPER directive.
747
748 content:
749
750 <html>
751 <head>
752 <title>[% template.title %]</title>
753 </head>
754
755 <body>
756 [% PROCESS $template %]
757 <hr>
758 © Copyright [% template.copyright %]
759 </body>
760 </html>
761
762 foo.html:
763
764 [% META
765 title = 'The Foo Page'
766 author = 'Fred Foo'
767 copyright = '2000 Fred Foo'
768 %]
769 <h1>[% template.title %]</h1>
770 Welcome to the Foo Page, blah blah blah
771
772 output:
773
774 <html>
775 <head>
776 <title>The Foo Page</title>
777 </head>
778
779 <body>
780 <h1>The Foo Page</h1>
781 Welcome to the Foo Page, blah blah blah
782 <hr>
783 © Copyright 2000 Fred Foo
784 </body>
785 </html>
786
787 WRAPPER
788 The WRAPPER option can be used to specify one or more templates
789 which should be used to wrap around the output of the main page
790 template. The main template is processed first (or any PROCESS
791 template(s)) and the output generated is then passed as the 'con‐
792 tent' variable to the WRAPPER template(s) as they are processed.
793
794 my $template = Template->new({
795 WRAPPER => 'wrapper',
796 };
797
798 # process 'foo' then wrap in 'wrapper'
799 $template->process('foo', { message => 'Hello World!' });
800
801 wrapper:
802
803 <wrapper>
804 [% content %]
805 </wrapper>
806
807 foo:
808
809 This is the foo file!
810 Message: [% message %]
811
812 The output generated from this example is:
813
814 <wrapper>
815 This is the foo file!
816 Message: Hello World!
817 </wrapper>
818
819 You can specify more than one WRAPPER template by setting the value
820 to be a reference to a list of templates. The WRAPPER templates
821 will be processed in reverse order with the output of each being
822 passed to the next (or previous, depending on how you look at it)
823 as the 'content' variable. It sounds complicated, but the end
824 result is that it just "Does The Right Thing" to make wrapper tem‐
825 plates nest in the order you specify.
826
827 my $template = Template->new({
828 WRAPPER => [ 'outer', 'inner' ],
829 };
830
831 # process 'foo' then wrap in 'inner', then in 'outer'
832 $template->process('foo', { message => 'Hello World!' });
833
834 outer:
835
836 <outer>
837 [% content %]
838 </outer>
839
840 inner:
841
842 <inner>
843 [% content %]
844 </inner>
845
846 The output generated is then:
847
848 <outer>
849 <inner>
850 This is the foo file!
851 Message: Hello World!
852 </inner>
853 </outer>
854
855 One side-effect of the "inside-out" processing of the WRAPPER con‐
856 figuration item (and also the WRAPPER directive) is that any vari‐
857 ables set in the template being wrapped will be visible to the tem‐
858 plate doing the wrapping, but not the other way around.
859
860 You can use this to good effect in allowing page templates to set
861 pre-defined values which are then used in the wrapper templates.
862 For example, our main page template 'foo' might look like this:
863
864 foo:
865
866 [% page = {
867 title = 'Foo Page'
868 subtitle = 'Everything There is to Know About Foo'
869 author = 'Frank Oliver Octagon'
870 }
871 %]
872
873 <p>
874 Welcome to the page that tells you everything about foo
875 blah blah blah...
876 </p>
877
878 The 'foo' template is processed before the wrapper template meaning
879 that the 'page' data structure will be defined for use in the wrap‐
880 per template.
881
882 wrapper:
883
884 <html>
885 <head>
886 <title>[% page.title %]</title>
887 </head>
888 <body>
889 <h1>[% page.title %]</h1>
890 <h2>[% page.subtitle %]</h1>
891 <h3>by [% page.author %]</h3>
892
893 [% content %]
894 </body>
895 </html>
896
897 It achieves the same effect as defining META items which are then
898 accessed via the 'template' variable (which you are still free to
899 use within WRAPPER templates), but gives you more flexibility in
900 the type and complexity of data that you can define.
901
902 ERROR
903 The ERROR (or ERRORS if you prefer) configuration item can be used
904 to name a single template or specify a hash array mapping exception
905 types to templates which should be used for error handling. If an
906 uncaught exception is raised from within a template then the appro‐
907 priate error template will instead be processed.
908
909 If specified as a single value then that template will be processed
910 for all uncaught exceptions.
911
912 my $template = Template->new({
913 ERROR => 'error.html'
914 });
915
916 If the ERROR item is a hash reference the keys are assumed to be
917 exception types and the relevant template for a given exception
918 will be selected. A 'default' template may be provided for the
919 general case. Note that 'ERROR' can be pluralised to 'ERRORS' if
920 you find it more appropriate in this case.
921
922 my $template = Template->new({
923 ERRORS => {
924 user => 'user/index.html',
925 dbi => 'error/database',
926 default => 'error/default',
927 },
928 });
929
930 In this example, any 'user' exceptions thrown will cause the
931 'user/index.html' template to be processed, 'dbi' errors are han‐
932 dled by 'error/database' and all others by the 'error/default' tem‐
933 plate. Any PRE_PROCESS and/or POST_PROCESS templates will also be
934 applied to these error templates.
935
936 Note that exception types are hierarchical and a 'foo' handler will
937 catch all 'foo.*' errors (e.g. foo.bar, foo.bar.baz) if a more spe‐
938 cific handler isn't defined. Be sure to quote any exception types
939 that contain periods to prevent Perl concatenating them into a sin‐
940 gle string (i.e. "user.passwd" is parsed as 'user'.'passwd').
941
942 my $template = Template->new({
943 ERROR => {
944 'user.login' => 'user/login.html',
945 'user.passwd' => 'user/badpasswd.html',
946 'user' => 'user/index.html',
947 'default' => 'error/default',
948 },
949 });
950
951 In this example, any template processed by the $template object, or
952 other templates or code called from within, can raise a
953 'user.login' exception and have the service redirect to the
954 'user/login.html' template. Similarly, a 'user.passwd' exception
955 has a specific handling template, 'user/badpasswd.html', while all
956 other 'user' or 'user.*' exceptions cause a redirection to the
957 'user/index.html' page. All other exception types are handled by
958 'error/default'.
959
960 Exceptions can be raised in a template using the THROW directive,
961
962 [% THROW user.login 'no user id: please login' %]
963
964 or by calling the throw() method on the current Template::Context
965 object,
966
967 $context->throw('user.passwd', 'Incorrect Password');
968 $context->throw('Incorrect Password'); # type 'undef'
969
970 or from Perl code by calling die() with a Template::Exception
971 object,
972
973 die (Template::Exception->new('user.denied', 'Invalid User ID'));
974
975 or by simply calling die() with an error string. This is automagi‐
976 cally caught and converted to an exception of 'undef' type which
977 can then be handled in the usual way.
978
979 die "I'm sorry Dave, I can't do that";
980
981 Template Runtime Options
982
983 EVAL_PERL
984 This flag is used to indicate if PERL and/or RAWPERL blocks should
985 be evaluated. By default, it is disabled and any PERL or RAWPERL
986 blocks encountered will raise exceptions of type 'perl' with the
987 message 'EVAL_PERL not set'. Note however that any RAWPERL blocks
988 should always contain valid Perl code, regardless of the EVAL_PERL
989 flag. The parser will fail to compile templates that contain
990 invalid Perl code in RAWPERL blocks and will throw a 'file' excep‐
991 tion.
992
993 When using compiled templates (see COMPILE_EXT and COMPILE_DIR),
994 the EVAL_PERL has an affect when the template is compiled, and
995 again when the templates is subsequently processed, possibly in a
996 different context to the one that compiled it.
997
998 If the EVAL_PERL is set when a template is compiled, then all PERL
999 and RAWPERL blocks will be included in the compiled template. If
1000 the EVAL_PERL option isn't set, then Perl code will be generated
1001 which always throws a 'perl' exception with the message 'EVAL_PERL
1002 not set' whenever the compiled template code is run.
1003
1004 Thus, you must have EVAL_PERL set if you want your compiled tem‐
1005 plates to include PERL and RAWPERL blocks.
1006
1007 At some point in the future, using a different invocation of the
1008 Template Toolkit, you may come to process such a pre-compiled tem‐
1009 plate. Assuming the EVAL_PERL option was set at the time the tem‐
1010 plate was compiled, then the output of any RAWPERL blocks will be
1011 included in the compiled template and will get executed when the
1012 template is processed. This will happen regardless of the runtime
1013 EVAL_PERL status.
1014
1015 Regular PERL blocks are a little more cautious, however. If the
1016 EVAL_PERL flag isn't set for the current context, that is, the one
1017 which is trying to process it, then it will throw the familiar
1018 'perl' exception with the message, 'EVAL_PERL not set'.
1019
1020 Thus you can compile templates to include PERL blocks, but option‐
1021 ally disable them when you process them later. Note however that
1022 it is possible for a PERL block to contain a Perl "BEGIN { # some
1023 code }" block which will always get run regardless of the runtime
1024 EVAL_PERL status. Thus, if you set EVAL_PERL when compiling tem‐
1025 plates, it is assumed that you trust the templates to Do The Right
1026 Thing. Otherwise you must accept the fact that there's no bullet‐
1027 proof way to prevent any included code from trampling around in the
1028 living room of the runtime environment, making a real nuisance of
1029 itself if it really wants to. If you don't like the idea of such
1030 uninvited guests causing a bother, then you can accept the default
1031 and keep EVAL_PERL disabled.
1032
1033 OUTPUT
1034 Default output location or handler. This may be specified as one
1035 of: a file name (relative to OUTPUT_PATH, if defined, or the cur‐
1036 rent working directory if not specified absolutely); a file handle
1037 (e.g. GLOB or IO::Handle) opened for writing; a reference to a text
1038 string to which the output is appended (the string isn't cleared);
1039 a reference to a subroutine which is called, passing the output
1040 text as an argument; as a reference to an array, onto which the
1041 content will be push()ed; or as a reference to any object that sup‐
1042 ports the print() method. This latter option includes the
1043 Apache::Request object which is passed as the argument to
1044 Apache/mod_perl handlers.
1045
1046 example 1 (file name):
1047
1048 my $template = Template->new({
1049 OUTPUT => "/tmp/foo",
1050 });
1051
1052 example 2 (text string):
1053
1054 my $output = '';
1055
1056 my $template = Template->new({
1057 OUTPUT => \$output,
1058 });
1059
1060 example 3 (file handle):
1061
1062 open (TOUT, "> $file") ⎪⎪ die "$file: $!\n";
1063
1064 my $template = Template->new({
1065 OUTPUT => \*TOUT,
1066 });
1067
1068 example 4 (subroutine):
1069
1070 sub output { my $out = shift; print "OUTPUT: $out" }
1071
1072 my $template = Template->new({
1073 OUTPUT => \&output,
1074 });
1075
1076 example 5 (array reference):
1077
1078 my $template = Template->new({
1079 OUTPUT => \@output,
1080 })
1081
1082 example 6 (Apache/mod_perl handler):
1083
1084 sub handler {
1085 my $r = shift;
1086
1087 my $t = Template->new({
1088 OUTPUT => $r,
1089 });
1090 ...
1091 }
1092
1093 The default OUTPUT location be overridden by passing a third param‐
1094 eter to the Template process() method. This can be specified as
1095 any of the above argument types.
1096
1097 $t->process($file, $vars, "/tmp/foo");
1098 $t->process($file, $vars, \$output);
1099 $t->process($file, $vars, \*MYGLOB);
1100 $t->process($file, $vars, \@output);
1101 $t->process($file, $vars, $r); # Apache::Request
1102 ...
1103
1104 OUTPUT_PATH
1105 The OUTPUT_PATH allows a directory to be specified into which out‐
1106 put files should be written. An output file can be specified by
1107 the OUTPUT option, or passed by name as the third parameter to the
1108 Template process() method.
1109
1110 my $template = Template->new({
1111 INCLUDE_PATH => "/tmp/src",
1112 OUTPUT_PATH => "/tmp/dest",
1113 });
1114
1115 my $vars = {
1116 ...
1117 };
1118
1119 foreach my $file ('foo.html', 'bar.html') {
1120 $template->process($file, $vars, $file)
1121 ⎪⎪ die $template->error();
1122 }
1123
1124 This example will read the input files '/tmp/src/foo.html' and
1125 '/tmp/src/bar.html' and write the processed output to
1126 '/tmp/dest/foo.html' and '/tmp/dest/bar.html', respectively.
1127
1128 DEBUG
1129 The DEBUG option can be used to enable debugging within the various
1130 different modules that comprise the Template Toolkit. The Tem‐
1131 plate::Constants module defines a set of DEBUG_XXXX constants which
1132 can be combined using the logical OR operator, '⎪'.
1133
1134 use Template::Constants qw( :debug );
1135
1136 my $template = Template->new({
1137 DEBUG => DEBUG_PARSER ⎪ DEBUG_PROVIDER,
1138 });
1139
1140 For convenience, you can also provide a string containing a list of
1141 lower case debug options, separated by any non-word characters.
1142
1143 my $template = Template->new({
1144 DEBUG => 'parser, provider',
1145 });
1146
1147 The following DEBUG_XXXX flags can be used:
1148
1149 DEBUG_SERVICE
1150 Enables general debugging messages for the Template::Service
1151 module.
1152
1153 DEBUG_CONTEXT
1154 Enables general debugging messages for the Template::Context
1155 module.
1156
1157 DEBUG_PROVIDER
1158 Enables general debugging messages for the Template::Provider
1159 module.
1160
1161 DEBUG_PLUGINS
1162 Enables general debugging messages for the Template::Plugins
1163 module.
1164
1165 DEBUG_FILTERS
1166 Enables general debugging messages for the Template::Filters
1167 module.
1168
1169 DEBUG_PARSER
1170 This flag causes the Template::Parser to generate debugging
1171 messages that show the Perl code generated by parsing and com‐
1172 piling each template.
1173
1174 DEBUG_UNDEF
1175 This option causes the Template Toolkit to throw an 'undef'
1176 error whenever it encounters an undefined variable value.
1177
1178 DEBUG_DIRS
1179 This option causes the Template Toolkit to generate comments
1180 indicating the source file, line and original text of each
1181 directive in the template. These comments are embedded in the
1182 template output using the format defined in the DEBUG_FORMAT
1183 configuration item, or a simple default format if unspecified.
1184
1185 For example, the following template fragment:
1186
1187 Hello World
1188
1189 would generate this output:
1190
1191 ## input text line 1 : ##
1192 Hello
1193 ## input text line 2 : World ##
1194 World
1195
1196 DEBUG_ALL
1197 Enables all debugging messages.
1198
1199 DEBUG_CALLER
1200 This option causes all debug messages that aren't newline ter‐
1201 minated to have the file name and line number of the caller
1202 appended to them.
1203
1204 DEBUG_FORMAT
1205 The DEBUG_FORMAT option can be used to specify a format string for
1206 the debugging messages generated via the DEBUG_DIRS option
1207 described above. Any occurances of $file, $line or $text will be
1208 replaced with the current file name, line or directive text,
1209 respectively. Notice how the format is single quoted to prevent
1210 Perl from interpolating those tokens as variables.
1211
1212 my $template = Template->new({
1213 DEBUG => 'dirs',
1214 DEBUG_FORMAT => '<!-- $file line $line : [% $text %] -->',
1215 });
1216
1217 The following template fragment:
1218
1219 [% foo = 'World' %]
1220 Hello [% foo %]
1221
1222 would then generate this output:
1223
1224 <!-- input text line 2 : [% foo = 'World' %] -->
1225 Hello <!-- input text line 3 : [% foo %] -->World
1226
1227 The DEBUG directive can also be used to set a debug format within a
1228 template.
1229
1230 [% DEBUG format '<!-- $file line $line : [% $text %] -->' %]
1231
1232 Caching and Compiling Options
1233
1234 CACHE_SIZE
1235 The Template::Provider module caches compiled templates to avoid
1236 the need to re-parse template files or blocks each time they are
1237 used. The CACHE_SIZE option is used to limit the number of com‐
1238 piled templates that the module should cache.
1239
1240 By default, the CACHE_SIZE is undefined and all compiled templates
1241 are cached. When set to any positive value, the cache will be lim‐
1242 ited to storing no more than that number of compiled templates.
1243 When a new template is loaded and compiled and the cache is full
1244 (i.e. the number of entries == CACHE_SIZE), the least recently used
1245 compiled template is discarded to make room for the new one.
1246
1247 The CACHE_SIZE can be set to 0 to disable caching altogether.
1248
1249 my $template = Template->new({
1250 CACHE_SIZE => 64, # only cache 64 compiled templates
1251 });
1252
1253 my $template = Template->new({
1254 CACHE_SIZE => 0, # don't cache any compiled templates
1255 });
1256
1257 COMPILE_EXT
1258 From version 2 onwards, the Template Toolkit has the ability to
1259 compile templates to Perl code and save them to disk for subsequent
1260 use (i.e. cache persistence). The COMPILE_EXT option may be pro‐
1261 vided to specify a filename extension for compiled template files.
1262 It is undefined by default and no attempt will be made to read or
1263 write any compiled template files.
1264
1265 my $template = Template->new({
1266 COMPILE_EXT => '.ttc',
1267 });
1268
1269 If COMPILE_EXT is defined (and COMPILE_DIR isn't, see below) then
1270 compiled template files with the COMPILE_EXT extension will be
1271 written to the same directory from which the source template files
1272 were loaded.
1273
1274 Compiling and subsequent reuse of templates happens automatically
1275 whenever the COMPILE_EXT or COMPILE_DIR options are set. The Tem‐
1276 plate Toolkit will automatically reload and reuse compiled files
1277 when it finds them on disk. If the corresponding source file has
1278 been modified since the compiled version as written, then it will
1279 load and re-compile the source and write a new compiled version to
1280 disk.
1281
1282 This form of cache persistence offers significant benefits in terms
1283 of time and resources required to reload templates. Compiled tem‐
1284 plates can be reloaded by a simple call to Perl's require(), leav‐
1285 ing Perl to handle all the parsing and compilation. This is a Good
1286 Thing.
1287
1288 COMPILE_DIR
1289 The COMPILE_DIR option is used to specify an alternate directory
1290 root under which compiled template files should be saved.
1291
1292 my $template = Template->new({
1293 COMPILE_DIR => '/tmp/ttc',
1294 });
1295
1296 The COMPILE_EXT option may also be specified to have a consistent
1297 file extension added to these files.
1298
1299 my $template1 = Template->new({
1300 COMPILE_DIR => '/tmp/ttc',
1301 COMPILE_EXT => '.ttc1',
1302 });
1303
1304 my $template2 = Template->new({
1305 COMPILE_DIR => '/tmp/ttc',
1306 COMPILE_EXT => '.ttc2',
1307 });
1308
1309 When COMPILE_EXT is undefined, the compiled template files have the
1310 same name as the original template files, but reside in a different
1311 directory tree.
1312
1313 Each directory in the INCLUDE_PATH is replicated in full beneath
1314 the COMPILE_DIR directory. This example:
1315
1316 my $template = Template->new({
1317 COMPILE_DIR => '/tmp/ttc',
1318 INCLUDE_PATH => '/home/abw/templates:/usr/share/templates',
1319 });
1320
1321 would create the following directory structure:
1322
1323 /tmp/ttc/home/abw/templates/
1324 /tmp/ttc/usr/share/templates/
1325
1326 Files loaded from different INCLUDE_PATH directories will have
1327 their compiled forms save in the relevant COMPILE_DIR directory.
1328
1329 On Win32 platforms a filename may by prefixed by a drive letter and
1330 colon. e.g.
1331
1332 C:/My Templates/header
1333
1334 The colon will be silently stripped from the filename when it is
1335 added to the COMPILE_DIR value(s) to prevent illegal filename being
1336 generated. Any colon in COMPILE_DIR elements will be left intact.
1337 For example:
1338
1339 # Win32 only
1340 my $template = Template->new({
1341 DELIMITER => ';',
1342 COMPILE_DIR => 'C:/TT2/Cache',
1343 INCLUDE_PATH => 'C:/TT2/Templates;D:/My Templates',
1344 });
1345
1346 This would create the following cache directories:
1347
1348 C:/TT2/Cache/C/TT2/Templates
1349 C:/TT2/Cache/D/My Templates
1350
1351 Plugins and Filters
1352
1353 PLUGINS
1354 The PLUGINS options can be used to provide a reference to a hash
1355 array that maps plugin names to Perl module names. A number of
1356 standard plugins are defined (e.g. 'table', 'cgi', 'dbi', etc.)
1357 which map to their corresponding Template::Plugin::* counterparts.
1358 These can be redefined by values in the PLUGINS hash.
1359
1360 my $template = Template->new({
1361 PLUGINS => {
1362 cgi => 'MyOrg::Template::Plugin::CGI',
1363 foo => 'MyOrg::Template::Plugin::Foo',
1364 bar => 'MyOrg::Template::Plugin::Bar',
1365 },
1366 });
1367
1368 The recommended convention is to specify these plugin names in
1369 lower case. The Template Toolkit first looks for an exact case-
1370 sensitive match and then tries the lower case conversion of the
1371 name specified.
1372
1373 [% USE Foo %] # look for 'Foo' then 'foo'
1374
1375 If you define all your PLUGINS with lower case names then they will
1376 be located regardless of how the user specifies the name in the USE
1377 directive. If, on the other hand, you define your PLUGINS with
1378 upper or mixed case names then the name specified in the USE direc‐
1379 tive must match the case exactly.
1380
1381 The USE directive is used to create plugin objects and does so by
1382 calling the plugin() method on the current Template::Context
1383 object. If the plugin name is defined in the PLUGINS hash then the
1384 corresponding Perl module is loaded via require(). The context
1385 then calls the load() class method which should return the class
1386 name (default and general case) or a prototype object against which
1387 the new() method can be called to instantiate individual plugin
1388 objects.
1389
1390 If the plugin name is not defined in the PLUGINS hash then the
1391 PLUGIN_BASE and/or LOAD_PERL options come into effect.
1392
1393 PLUGIN_BASE
1394 If a plugin is not defined in the PLUGINS hash then the PLUGIN_BASE
1395 is used to attempt to construct a correct Perl module name which
1396 can be successfully loaded.
1397
1398 The PLUGIN_BASE can be specified as a reference to an array of mod‐
1399 ule namespaces, or as a single value which is automatically con‐
1400 verted to a list. The default PLUGIN_BASE value ('Template::Plug‐
1401 in') is then added to the end of this list.
1402
1403 example 1:
1404
1405 my $template = Template->new({
1406 PLUGIN_BASE => 'MyOrg::Template::Plugin',
1407 });
1408
1409 [% USE Foo %] # => MyOrg::Template::Plugin::Foo
1410 or Template::Plugin::Foo
1411
1412 example 2:
1413
1414 my $template = Template->new({
1415 PLUGIN_BASE => [ 'MyOrg::Template::Plugin',
1416 'YourOrg::Template::Plugin' ],
1417 });
1418
1419 [% USE Foo %] # => MyOrg::Template::Plugin::Foo
1420 or YourOrg::Template::Plugin::Foo
1421 or Template::Plugin::Foo
1422
1423 If you don't want the default Template::Plugin namespace added to
1424 the end of the PLUGIN_BASE, then set the $Template::Plugins::PLUG‐
1425 IN_BASE variable to a false value before calling the Template new()
1426 constructor method. This is shown in the example below where the
1427 'Foo' is located as 'My::Plugin::Foo' or 'Your::Plugin::Foo' but
1428 not as 'Template::Plugin::Foo'.
1429
1430 example 3:
1431
1432 use Template::Plugins;
1433 $Template::Plugins::PLUGIN_BASE = '';
1434
1435 my $template = Template->new({
1436 PLUGIN_BASE => [ 'My::Plugin',
1437 'Your::Plugin' ],
1438 });
1439
1440 [% USE Foo %] # => My::Plugin::Foo
1441 or Your::Plugin::Foo
1442
1443 LOAD_PERL
1444 If a plugin cannot be loaded using the PLUGINS or PLUGIN_BASE
1445 approaches then the provider can make a final attempt to load the
1446 module without prepending any prefix to the module path. This
1447 allows regular Perl modules (i.e. those that don't reside in the
1448 Template::Plugin or some other such namespace) to be loaded and
1449 used as plugins.
1450
1451 By default, the LOAD_PERL option is set to 0 and no attempt will be
1452 made to load any Perl modules that aren't named explicitly in the
1453 PLUGINS hash or reside in a package as named by one of the PLUG‐
1454 IN_BASE components.
1455
1456 Plugins loaded using the PLUGINS or PLUGIN_BASE receive a reference
1457 to the current context object as the first argument to the new()
1458 constructor. Modules loaded using LOAD_PERL are assumed to not
1459 conform to the plugin interface. They must provide a new() class
1460 method for instantiating objects but it will not receive a refer‐
1461 ence to the context as the first argument. Plugin modules should
1462 provide a load() class method (or inherit the default one from the
1463 Template::Plugin base class) which is called the first time the
1464 plugin is loaded. Regular Perl modules need not. In all other
1465 respects, regular Perl objects and Template Toolkit plugins are
1466 identical.
1467
1468 If a particular Perl module does not conform to the common, but not
1469 unilateral, new() constructor convention then a simple plugin wrap‐
1470 per can be written to interface to it.
1471
1472 FILTERS
1473 The FILTERS option can be used to specify custom filters which can
1474 then be used with the FILTER directive like any other. These are
1475 added to the standard filters which are available by default. Fil‐
1476 ters specified via this option will mask any standard filters of
1477 the same name.
1478
1479 The FILTERS option should be specified as a reference to a hash
1480 array in which each key represents the name of a filter. The cor‐
1481 responding value should contain a reference to an array containing
1482 a subroutine reference and a flag which indicates if the filter is
1483 static (0) or dynamic (1). A filter may also be specified as a
1484 solitary subroutine reference and is assumed to be static.
1485
1486 $template = Template->new({
1487 FILTERS => {
1488 'sfilt1' => \&static_filter, # static
1489 'sfilt2' => [ \&static_filter, 0 ], # same as above
1490 'dfilt1' => [ \&dyanamic_filter_factory, 1 ],
1491 },
1492 });
1493
1494 Additional filters can be specified at any time by calling the
1495 define_filter() method on the current Template::Context object.
1496 The method accepts a filter name, a reference to a filter subrou‐
1497 tine and an optional flag to indicate if the filter is dynamic.
1498
1499 my $context = $template->context();
1500 $context->define_filter('new_html', \&new_html);
1501 $context->define_filter('new_repeat', \&new_repeat, 1);
1502
1503 Static filters are those where a single subroutine reference is
1504 used for all invocations of a particular filter. Filters that
1505 don't accept any configuration parameters (e.g. 'html') can be
1506 implemented statically. The subroutine reference is simply
1507 returned when that particular filter is requested. The subroutine
1508 is called to filter the output of a template block which is passed
1509 as the only argument. The subroutine should return the modified
1510 text.
1511
1512 sub static_filter {
1513 my $text = shift;
1514 # do something to modify $text...
1515 return $text;
1516 }
1517
1518 The following template fragment:
1519
1520 [% FILTER sfilt1 %]
1521 Blah blah blah.
1522 [% END %]
1523
1524 is approximately equivalent to:
1525
1526 &static_filter("\nBlah blah blah.\n");
1527
1528 Filters that can accept parameters (e.g. 'truncate') should be
1529 implemented dynamically. In this case, the subroutine is taken to
1530 be a filter 'factory' that is called to create a unique filter sub‐
1531 routine each time one is requested. A reference to the current
1532 Template::Context object is passed as the first parameter, followed
1533 by any additional parameters specified. The subroutine should
1534 return another subroutine reference (usually a closure) which
1535 implements the filter.
1536
1537 sub dynamic_filter_factory {
1538 my ($context, @args) = @_;
1539
1540 return sub {
1541 my $text = shift;
1542 # do something to modify $text...
1543 return $text;
1544 }
1545 }
1546
1547 The following template fragment:
1548
1549 [% FILTER dfilt1(123, 456) %]
1550 Blah blah blah
1551 [% END %]
1552
1553 is approximately equivalent to:
1554
1555 my $filter = &dynamic_filter_factory($context, 123, 456);
1556 &$filter("\nBlah blah blah.\n");
1557
1558 See the FILTER directive for further examples.
1559
1560 Compatibility, Customisation and Extension
1561
1562 V1DOLLAR
1563 In version 1 of the Template Toolkit, an optional leading '$' could
1564 be placed on any template variable and would be silently ignored.
1565
1566 # VERSION 1
1567 [% $foo %] === [% foo %]
1568 [% $hash.$key %] === [% hash.key %]
1569
1570 To interpolate a variable value the '${' ... '}' construct was
1571 used. Typically, one would do this to index into a hash array when
1572 the key value was stored in a variable.
1573
1574 example:
1575
1576 my $vars = {
1577 users => {
1578 aba => { name => 'Alan Aardvark', ... },
1579 abw => { name => 'Andy Wardley', ... },
1580 ...
1581 },
1582 uid => 'aba',
1583 ...
1584 };
1585
1586 $template->process('user/home.html', $vars)
1587 ⎪⎪ die $template->error(), "\n";
1588
1589 'user/home.html':
1590
1591 [% user = users.${uid} %] # users.aba
1592 Name: [% user.name %] # Alan Aardvark
1593
1594 This was inconsistent with double quoted strings and also the
1595 INTERPOLATE mode, where a leading '$' in text was enough to indi‐
1596 cate a variable for interpolation, and the additional curly braces
1597 were used to delimit variable names where necessary. Note that
1598 this use is consistent with UNIX and Perl conventions, among oth‐
1599 ers.
1600
1601 # double quoted string interpolation
1602 [% name = "$title ${user.name}" %]
1603
1604 # INTERPOLATE = 1
1605 <img src="$images/help.gif"></a>
1606 <img src="$images/${icon.next}.gif">
1607
1608 For version 2, these inconsistencies have been removed and the syn‐
1609 tax clarified. A leading '$' on a variable is now used exclusively
1610 to indicate that the variable name should be interpolated (e.g.
1611 subsituted for its value) before being used. The earlier example
1612 from version 1:
1613
1614 # VERSION 1
1615 [% user = users.${uid} %]
1616 Name: [% user.name %]
1617
1618 can now be simplified in version 2 as:
1619
1620 # VERSION 2
1621 [% user = users.$uid %]
1622 Name: [% user.name %]
1623
1624 The leading dollar is no longer ignored and has the same effect of
1625 interpolation as '${' ... '}' in version 1. The curly braces may
1626 still be used to explicitly scope the interpolated variable name
1627 where necessary.
1628
1629 e.g.
1630
1631 [% user = users.${me.id} %]
1632 Name: [% user.name %]
1633
1634 The rule applies for all variables, both within directives and in
1635 plain text if processed with the INTERPOLATE option. This means
1636 that you should no longer (if you ever did) add a leading '$' to a
1637 variable inside a directive, unless you explicitly want it to be
1638 interpolated.
1639
1640 One obvious side-effect is that any version 1 templates with vari‐
1641 ables using a leading '$' will no longer be processed as expected.
1642 Given the following variable definitions,
1643
1644 [% foo = 'bar'
1645 bar = 'baz'
1646 %]
1647
1648 version 1 would interpret the following as:
1649
1650 # VERSION 1
1651 [% $foo %] => [% GET foo %] => bar
1652
1653 whereas version 2 interprets it as:
1654
1655 # VERSION 2
1656 [% $foo %] => [% GET $foo %] => [% GET bar %] => baz
1657
1658 In version 1, the '$' is ignored and the value for the variable
1659 'foo' is retrieved and printed. In version 2, the variable '$foo'
1660 is first interpolated to give the variable name 'bar' whose value
1661 is then retrieved and printed.
1662
1663 The use of the optional '$' has never been strongly recommended,
1664 but to assist in backwards compatibility with any version 1 tem‐
1665 plates that may rely on this "feature", the V1DOLLAR option can be
1666 set to 1 (default: 0) to revert the behaviour and have leading '$'
1667 characters ignored.
1668
1669 my $template = Template->new({
1670 V1DOLLAR => 1,
1671 });
1672
1673 LOAD_TEMPLATES
1674 The LOAD_TEMPLATE option can be used to provide a reference to a
1675 list of Template::Provider objects or sub-classes thereof which
1676 will take responsibility for loading and compiling templates.
1677
1678 my $template = Template->new({
1679 LOAD_TEMPLATES => [
1680 MyOrg::Template::Provider->new({ ... }),
1681 Template::Provider->new({ ... }),
1682 ],
1683 });
1684
1685 When a PROCESS, INCLUDE or WRAPPER directive is encountered, the
1686 named template may refer to a locally defined BLOCK or a file rela‐
1687 tive to the INCLUDE_PATH (or an absolute or relative path if the
1688 appropriate ABSOLUTE or RELATIVE options are set). If a BLOCK def‐
1689 inition can't be found (see the Template::Context template() method
1690 for a discussion of BLOCK locality) then each of the LOAD_TEMPLATES
1691 provider objects is queried in turn via the fetch() method to see
1692 if it can supply the required template. Each provider can return a
1693 compiled template, an error, or decline to service the request in
1694 which case the responsibility is passed to the next provider. If
1695 none of the providers can service the request then a 'not found'
1696 error is returned. The same basic provider mechanism is also used
1697 for the INSERT directive but it bypasses any BLOCK definitions and
1698 doesn't attempt is to parse or process the contents of the template
1699 file.
1700
1701 This is an implementation of the 'Chain of Responsibility' design
1702 pattern as described in "Design Patterns", Erich Gamma, Richard
1703 Helm, Ralph Johnson, John Vlissides), Addision-Wesley, ISBN
1704 0-201-63361-2, page 223 .
1705
1706 If LOAD_TEMPLATES is undefined, a single default provider will be
1707 instantiated using the current configuration parameters. For exam‐
1708 ple, the Template::Provider INCLUDE_PATH option can be specified in
1709 the Template configuration and will be correctly passed to the
1710 provider's constructor method.
1711
1712 my $template = Template->new({
1713 INCLUDE_PATH => '/here:/there',
1714 });
1715
1716 LOAD_PLUGINS
1717 The LOAD_PLUGINS options can be used to specify a list of provider
1718 objects (i.e. they implement the fetch() method) which are respon‐
1719 sible for loading and instantiating template plugin objects. The
1720 Template::Content plugin() method queries each provider in turn in
1721 a "Chain of Responsibility" as per the template() and filter()
1722 methods.
1723
1724 my $template = Template->new({
1725 LOAD_PLUGINS => [
1726 MyOrg::Template::Plugins->new({ ... }),
1727 Template::Plugins->new({ ... }),
1728 ],
1729 });
1730
1731 By default, a single Template::Plugins object is created using the
1732 current configuration hash. Configuration items destined for the
1733 Template::Plugins constructor may be added to the Template con‐
1734 structor.
1735
1736 my $template = Template->new({
1737 PLUGIN_BASE => 'MyOrg::Template::Plugins',
1738 LOAD_PERL => 1,
1739 });
1740
1741 LOAD_FILTERS
1742 The LOAD_FILTERS option can be used to specify a list of provider
1743 objects (i.e. they implement the fetch() method) which are respon‐
1744 sible for returning and/or creating filter subroutines. The Tem‐
1745 plate::Context filter() method queries each provider in turn in a
1746 "Chain of Responsibility" as per the template() and plugin() meth‐
1747 ods.
1748
1749 my $template = Template->new({
1750 LOAD_FILTERS => [
1751 MyTemplate::Filters->new(),
1752 Template::Filters->new(),
1753 ],
1754 });
1755
1756 By default, a single Template::Filters object is created for the
1757 LOAD_FILTERS list.
1758
1759 TOLERANT
1760 The TOLERANT flag is used by the various Template Toolkit provider
1761 modules (Template::Provider, Template::Plugins, Template::Filters)
1762 to control their behaviour when errors are encountered. By
1763 default, any errors are reported as such, with the request for the
1764 particular resource (template, plugin, filter) being denied and an
1765 exception raised. When the TOLERANT flag is set to any true val‐
1766 ues, errors will be silently ignored and the provider will instead
1767 return STATUS_DECLINED. This allows a subsequent provider to take
1768 responsibility for providing the resource, rather than failing the
1769 request outright. If all providers decline to service the request,
1770 either through tolerated failure or a genuine disinclination to
1771 comply, then a '<resource> not found' exception is raised.
1772
1773 SERVICE
1774 A reference to a Template::Service object, or sub-class thereof, to
1775 which the Template module should delegate. If unspecified, a Tem‐
1776 plate::Service object is automatically created using the current
1777 configuration hash.
1778
1779 my $template = Template->new({
1780 SERVICE => MyOrg::Template::Service->new({ ... }),
1781 });
1782
1783 CONTEXT
1784 A reference to a Template::Context object which is used to define a
1785 specific environment in which template are processed. A Tem‐
1786 plate::Context object is passed as the only parameter to the Perl
1787 subroutines that represent "compiled" template documents. Template
1788 subroutines make callbacks into the context object to access Tem‐
1789 plate Toolkit functionality, for example, to to INCLUDE or PROCESS
1790 another template (include() and process() methods, respectively),
1791 to USE a plugin (plugin()) or instantiate a filter (filter()) or to
1792 access the stash (stash()) which manages variable definitions via
1793 the get() and set() methods.
1794
1795 my $template = Template->new({
1796 CONTEXT => MyOrg::Template::Context->new({ ... }),
1797 });
1798
1799 STASH
1800 A reference to a Template::Stash object or sub-class which will
1801 take responsibility for managing template variables.
1802
1803 my $stash = MyOrg::Template::Stash->new({ ... });
1804 my $template = Template->new({
1805 STASH => $stash,
1806 });
1807
1808 If unspecified, a default stash object is created using the VARI‐
1809 ABLES configuration item to initialise the stash variables. These
1810 may also be specified as the PRE_DEFINE option for backwards com‐
1811 patibility with version 1.
1812
1813 my $template = Template->new({
1814 VARIABLES => {
1815 id => 'abw',
1816 name => 'Andy Wardley',
1817 },
1818 };
1819
1820 PARSER
1821 The Template::Parser module implements a parser object for compil‐
1822 ing templates into Perl code which can then be executed. A default
1823 object of this class is created automatically and then used by the
1824 Template::Provider whenever a template is loaded and requires com‐
1825 pilation. The PARSER option can be used to provide a reference to
1826 an alternate parser object.
1827
1828 my $template = Template->new({
1829 PARSER => MyOrg::Template::Parser->new({ ... }),
1830 });
1831
1832 GRAMMAR
1833 The GRAMMAR configuration item can be used to specify an alternate
1834 grammar for the parser. This allows a modified or entirely new
1835 template language to be constructed and used by the Template Tool‐
1836 kit.
1837
1838 Source templates are compiled to Perl code by the Template::Parser
1839 using the Template::Grammar (by default) to define the language
1840 structure and semantics. Compiled templates are thus inherently
1841 "compatible" with each other and there is nothing to prevent any
1842 number of different template languages being compiled and used
1843 within the same Template Toolkit processing environment (other than
1844 the usual time and memory constraints).
1845
1846 The Template::Grammar file is constructed from a YACC like grammar
1847 (using Parse::YAPP) and a skeleton module template. These files
1848 are provided, along with a small script to rebuild the grammar, in
1849 the 'parser' sub-directory of the distribution. You don't have to
1850 know or worry about these unless you want to hack on the template
1851 language or define your own variant. There is a README file in the
1852 same directory which provides some small guidance but it is assumed
1853 that you know what you're doing if you venture herein. If you grok
1854 LALR parsers, then you should find it comfortably familiar.
1855
1856 By default, an instance of the default Template::Grammar will be
1857 created and used automatically if a GRAMMAR item isn't specified.
1858
1859 use MyOrg::Template::Grammar;
1860
1861 my $template = Template->new({
1862 GRAMMAR = MyOrg::Template::Grammar->new();
1863 });
1864
1866 Andy Wardley <abw@wardley.org>
1867
1868 <http://wardley.org/⎪http://wardley.org/>
1869
1871 Template Toolkit version 2.18, released on 09 February 2007.
1872
1874 Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
1875
1876 This module is free software; you can redistribute it and/or modify it
1877 under the same terms as Perl itself.
1878
1879
1880
1881perl v5.8.8 2007-02-09 Template::Manual::Config(3)