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