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