1 .\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.3
4 .\" ========================================================================
5 .de Sh \" Subsection heading
13 .de Sp \" Vertical space (when we can't use .PP)
17 .de Vb \" Begin verbatim text
22 .de Ve \" End verbatim text
26 .\" Set up some character translations and predefined strings. \*(-- will
27 .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28 .\" double quote, and \*(R" will give a right double quote. | will give a
29 .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30 .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31 .\" expand to `' in nroff, nothing in troff, for use with C<>.
33 .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
37 . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38 . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
51 .\" If the F register is turned on, we'll generate index entries on stderr for
52 .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53 .\" entries marked with X<> in POD. Of course, you'll have to process the
54 .\" output yourself in some meaningful fashion.
57 . tm Index:\\$1\t\\n%\t"\\$2"
63 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
64 .\" way too many mistakes in technical documents.
68 .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69 .\" Fear. Run. Save yourself. No user-serviceable parts.
70 . \" fudge factors for nroff and troff
79 . ds #H ((1u-(\\\\n(.fu%2u))*.13m)
85 . \" simple accents for nroff and troff
95 . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96 . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97 . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98 . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99 . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100 . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
102 . \" troff and (daisy-wheel) nroff accents
103 .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104 .ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105 .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106 .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107 .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108 .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109 .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110 .ds ae a\h'-(\w'a'u*4/10)'e
111 .ds Ae A\h'-(\w'A'u*4/10)'E
112 . \" corrections for vroff
113 .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114 .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115 . \" for low resolution devices (crt and lpr)
116 .if \n(.H>23 .if \n(.V>19 \
129 .\" ========================================================================
131 .IX Title "Template::Manual::Directives 3"
132 .TH Template::Manual::Directives 3 "2008-11-13" "perl v5.8.7" "User Contributed Perl Documentation"
134 Template::Manual::Directives \- Template directives
135 .SH "Accessing and Updating Template Variables"
136 .IX Header "Accessing and Updating Template Variables"
139 The \f(CW\*(C`GET\*(C'\fR directive retrieves and outputs the value of the named variable.
145 The \f(CW\*(C`GET\*(C'\fR keyword is optional. A variable can be specified in a directive
152 The variable can have an unlimited number of elements, each separated by a
153 dot. Each element can have arguments specified within parentheses.
162 See Template::Manual::Variables for a full discussion on template
165 You can also specify expressions using the logical (\f(CW\*(C`and\*(C'\fR, \f(CW\*(C`or\*(C'\fR, \f(CW\*(C`not\*(C'\fR, \f(CW\*(C`?\*(C'\fR, \f(CW\*(C`:\*(C'\fR) and
166 mathematic operators (\f(CW\*(C`+\*(C'\fR, \f(CW\*(C`\-\*(C'\fR, \f(CW\*(C`*\*(C'\fR, \f(CW\*(C`/\*(C'\fR, \f(CW\*(C`%\*(C'\fR, \f(CW\*(C`mod\*(C'\fR, \f(CW\*(C`div\*(C'\fR).
169 \& [% template.title or default.title %]
177 \& [% order.nitems ? checkout(order.total) : 'no items' %]
180 The \f(CW\*(C`div\*(C'\fR operator returns the integer result of division. Both \f(CW\*(C`%\*(C'\fR and
181 \&\f(CW\*(C`mod\*(C'\fR return the modulus (i.e. remainder) of division.
184 \& [% 15 / 6 %] # 2.5
185 \& [% 15 div 6 %] # 2
186 \& [% 15 mod 6 %] # 3
189 .IX Subsection "CALL"
190 The \f(CW\*(C`CALL\*(C'\fR directive is similar to \f(CW\*(C`GET\*(C'\fR in evaluating the variable named,
191 but doesn't print the result returned. This can be useful when a
192 variable is bound to a sub-routine or object method which you want to
193 call but aren't interested in the value returned.
196 \& [% CALL dbi.disconnect %]
200 \& [% CALL inc_page_counter(page_count) %]
204 The \f(CW\*(C`SET\*(C'\fR directive allows you to assign new values to existing variables
205 or create new temporary variables.
208 \& [% SET title = 'Hello World' %]
211 The \f(CW\*(C`SET\*(C'\fR keyword is also optional.
214 \& [% title = 'Hello World' %]
217 Variables may be assigned the values of other variables, unquoted
218 numbers (2.718), literal text ('single quotes') or quoted text
219 (\*(L"double quotes\*(R"). In the latter case, any variable references within
220 the text will be interpolated when the string is evaluated. Variables
221 should be prefixed by \f(CW\*(C`$\*(C'\fR, using curly braces to explicitly scope
222 the variable name where necessary.
225 \& [% foo = 'Foo' %] # literal value 'Foo'
226 \& [% bar = foo %] # value of variable 'foo'
227 \& [% cost = '$100' %] # literal value '$100'
228 \& [% item = "$bar: ${cost}.00" %] # value "Foo: $100.00"
231 Multiple variables may be assigned in the same directive and are
232 evaluated in the order specified. Thus, the above could have been
239 \& item = "$bar: ${cost}.00"
243 Simple expressions can also be used, as per \f(CW\*(C`GET\*(C'\fR.
248 \& thirty = twenty + ten
249 \& forty = 2 * twenty
251 \& six = twenty mod 7
255 You can concatenate strings together using the \f(CW' _ '\fR operator. In Perl 5,
256 the \f(CW\*(C`.\*(C'\fR is used for string concatenation, but in Perl 6, as in the Template
257 Toolkit, the \f(CW\*(C`.\*(C'\fR will be used as the method calling operator and \f(CW' _ '\fR will
258 be used for string concatenation. Note that the operator must be
259 specified with surrounding whitespace which, as Larry says, is construed as
263 \& [% copyright = '(C) Copyright' _ year _ ' ' _ author %]
266 You can, of course, achieve a similar effect with double quoted string
270 \& [% copyright = "(C) Copyright $year $author" %]
273 .IX Subsection "DEFAULT"
274 The \f(CW\*(C`DEFAULT\*(C'\fR directive is similar to \f(CW\*(C`SET\*(C'\fR but only updates variables
275 that are currently undefined or have no \*(L"true\*(R" value (in the Perl
285 This can be particularly useful in common template components to
286 ensure that some sensible default are provided for otherwise
291 \& title = 'Hello World'
296 \& <title>[% title %]</title>
298 \& <body bgcolor="[% bgcol %]">
301 .SH "Processing Template Files and Blocks"
302 .IX Header "Processing Template Files and Blocks"
304 .IX Subsection "INSERT"
305 The \f(CW\*(C`INSERT\*(C'\fR directive is used to insert the contents of an external file
306 at the current position.
309 \& [% INSERT myfile %]
312 No attempt to parse or process the file is made. The contents,
313 possibly including any embedded template directives, are inserted
316 The filename specified should be relative to one of the \f(CW\*(C`INCLUDE_PATH\*(C'\fR
317 directories. Absolute (i.e. starting with \f(CW\*(C`/\*(C'\fR) and relative
318 (i.e. starting with \f(CW\*(C`.\*(C'\fR) filenames may be used if the \f(CW\*(C`ABSOLUTE\*(C'\fR and
319 \&\f(CW\*(C`RELATIVE\*(C'\fR options are set, respectively. Both these options are
323 \& my $template = Template\->new({
324 \& INCLUDE_PATH => '/here:/there',
329 \& $template\->process('myfile');
335 \& [% INSERT foo %] # looks for /here/foo then /there/foo
336 \& [% INSERT /etc/passwd %] # file error: ABSOLUTE not set
337 \& [% INSERT ../secret %] # file error: RELATIVE not set
340 For convenience, the filename does not need to be quoted as long as it
341 contains only alphanumeric characters, underscores, dots or forward
342 slashes. Names containing any other characters should be quoted.
345 \& [% INSERT misc/legalese.txt %]
346 \& [% INSERT 'dos98/Program Files/stupid' %]
349 To evaluate a variable to specify a filename, you should explicitly
350 prefix it with a \f(CW\*(C`$\*(C'\fR or use double-quoted string interpolation.
353 \& [% language = 'en'
354 \& legalese = 'misc/legalese.txt'
359 \& [% INSERT $legalese %] # misc/legalese.txt
360 \& [% INSERT "$language/$legalese" %] # en/misc/legalese.txt
363 Multiple files can be specified using \f(CW\*(C`+\*(C'\fR as a delimiter. All files
364 should be unquoted names or quoted strings. Any variables should be
365 interpolated into double-quoted strings.
368 \& [% INSERT legalese.txt + warning.txt %]
369 \& [% INSERT "$legalese" + warning.txt %] # requires quoting
372 .IX Subsection "INCLUDE"
373 The \f(CW\*(C`INCLUDE\*(C'\fR directive is used to process and include the output of
374 another template file or block.
377 \& [% INCLUDE header %]
380 If a \f(CW\*(C`BLOCK\*(C'\fR of the specified name is defined in the same file, or in a file
381 from which the current template has been called (i.e. a parent template) then
382 it will be used in preference to any file of the same name.
385 \& [% INCLUDE table %] # uses BLOCK defined below
396 If a \f(CW\*(C`BLOCK\*(C'\fR definition is not currently visible then the template name
397 should be a file relative to one of the \f(CW\*(C`INCLUDE_PATH\*(C'\fR directories, or
398 an absolute or relative file name if the \f(CW\*(C`ABSOLUTE\*(C'\fR/\f(CW\*(C`RELATIVE\*(C'\fR options are
399 appropriately enabled. The \f(CW\*(C`INCLUDE\*(C'\fR directive automatically quotes the
400 filename specified, as per \f(CW\*(C`INSERT\*(C'\fR described above. When a variable
401 contains the name of the template for the \f(CW\*(C`INCLUDE\*(C'\fR directive, it should
402 be explicitly prefixed by \f(CW\*(C`$\*(C'\fR or double-quoted
405 \& [% myheader = 'my/misc/header' %]
406 \& [% INCLUDE myheader %] # 'myheader'
407 \& [% INCLUDE $myheader %] # 'my/misc/header'
408 \& [% INCLUDE "$myheader" %] # 'my/misc/header'
411 Any template directives embedded within the file will be processed
412 accordingly. All variables currently defined will be visible and
413 accessible from within the included template.
416 \& [% title = 'Hello World' %]
417 \& [% INCLUDE header %]
426 \& <title>[% title %]</title>
433 \& <title>Hello World</title>
438 Local variable definitions may be specified after the template name,
439 temporarily masking any existing variables. Insignificant whitespace
440 is ignored within directives so you can add variable definitions on the
441 same line, the next line or split across several line with comments
442 interspersed, if you prefer.
445 \& [% INCLUDE table %]
449 \& [% INCLUDE table title="Active Projects" %]
454 \& title = "Active Projects"
455 \& bgcolor = "#80ff00" # chartreuse
460 The \f(CW\*(C`INCLUDE\*(C'\fR directive localises (i.e. copies) all variables before
461 processing the template. Any changes made within the included
462 template will not affect variables in the including template.
469 \& foo is originally [% foo %]
471 \& foo is still [% foo %]
478 \& foo is now [% foo %]
485 \& foo is originally 10
491 Technical Note: the localisation of the stash (that is, the process by
492 which variables are copied before an \f(CW\*(C`INCLUDE\*(C'\fR to prevent being
493 overwritten) is only skin deep. The top-level variable namespace
494 (hash) is copied, but no attempt is made to perform a deep-copy of
495 other structures (hashes, arrays, objects, etc.) Therefore, a \f(CW\*(C`foo\*(C'\fR
496 variable referencing a hash will be copied to create a new \f(CW\*(C`foo\*(C'\fR
497 variable but which points to the same hash array. Thus, if you update
498 compound variables (e.g. \f(CW\*(C`foo.bar\*(C'\fR) then you will change the original
499 copy, regardless of any stash localisation. If you're not worried
500 about preserving variable values, or you trust the templates you're
501 including then you might prefer to use the \f(CW\*(C`PROCESS\*(C'\fR directive which is
502 faster by virtue of not performing any localisation.
504 You can specify dotted variables as \*(L"local\*(R" variables to an \f(CW\*(C`INCLUDE\*(C'\fR directive.
505 However, be aware that because of the localisation issues explained above (if
506 you skipped the previous Technical Note above then you might want to go back
507 and read it or skip this section too), the variables might not actualy be
508 \&\*(L"local\*(R". If the first element of the variable name already references a hash
509 array then the variable update will affect the original variable.
519 \& [% INCLUDE somefile foo.bar='Boz' %]
523 \& [% foo.bar %] # Boz
526 This behaviour can be a little unpredictable (and may well be improved
527 upon in a future version). If you know what you're doing with it and
528 you're sure that the variables in question are defined (nor not) as you
529 expect them to be, then you can rely on this feature to implement some
530 powerful \*(L"global\*(R" data sharing techniques. Otherwise, you might prefer
531 to steer well clear and always pass simple (undotted) variables as
532 parameters to \f(CW\*(C`INCLUDE\*(C'\fR and other similar directives.
534 If you want to process several templates in one go then you can
535 specify each of their names (quoted or unquoted names only, no unquoted
536 \&\f(CW$variables\fR) joined together by \f(CW\*(C`+\*(C'\fR. The \f(CW\*(C`INCLUDE\*(C'\fR directive
537 will then process them in order.
540 \& [% INCLUDE html/header + "site/$header" + site/menu
541 \& title = "My Groovy Web Site"
545 The variable stash is localised once and then the templates specified
546 are processed in order, all within that same variable context. This
547 makes it slightly faster than specifying several separate \f(CW\*(C`INCLUDE\*(C'\fR
548 directives (because you only clone the variable stash once instead of
549 n times), but not quite as \*(L"safe\*(R" because any variable changes in the
550 first file will be visible in the second, third and so on. This
551 might be what you want, of course, but then again, it might not.
553 .IX Subsection "PROCESS"
554 The \s-1PROCESS\s0 directive is similar to \f(CW\*(C`INCLUDE\*(C'\fR but does not perform any
555 localisation of variables before processing the template. Any changes
556 made to variables within the included template will be visible in the
572 \& changed foo to [% foo %]
584 Parameters may be specified in the \f(CW\*(C`PROCESS\*(C'\fR directive, but these too will
585 become visible changes to current variable values.
598 \& this is bar, foo is [% foo %]
606 \& this is bar, foo is 20
610 The \f(CW\*(C`PROCESS\*(C'\fR directive is slightly faster than \f(CW\*(C`INCLUDE\*(C'\fR because it
611 avoids the need to localise (i.e. copy) the variable stash before
612 processing the template. As with \f(CW\*(C`INSERT\*(C'\fR and \f(CW\*(C`INCLUDE\*(C'\fR, the first
613 parameter does not need to be quoted as long as it contains only
614 alphanumeric characters, underscores, periods or forward slashes.
615 A \f(CW\*(C`$\*(C'\fR prefix can be used to explicitly indicate a variable which
616 should be interpolated to provide the template name:
619 \& [% myheader = 'my/misc/header' %]
620 \& [% PROCESS myheader %] # 'myheader'
621 \& [% PROCESS $myheader %] # 'my/misc/header'
624 As with \f(CW\*(C`INCLUDE\*(C'\fR, multiple templates can be specified, delimited by
625 \&\f(CW\*(C`+\*(C'\fR, and are processed in order.
628 \& [% PROCESS html/header + my/header %]
631 .IX Subsection "WRAPPER"
632 It's not unusual to find yourself adding common headers and footers to
633 pages or sub-sections within a page. Something like this:
636 \& [% INCLUDE section/header
637 \& title = 'Quantum Mechanics'
639 \& Quantum mechanics is a very interesting subject wish
640 \& should prove easy for the layman to fully comprehend.
641 \& [% INCLUDE section/footer %]
645 \& [% INCLUDE section/header
646 \& title = 'Desktop Nuclear Fusion for under $50'
648 \& This describes a simple device which generates significant
649 \& sustainable electrical power from common tap water by process
650 \& of nuclear fusion.
651 \& [% INCLUDE section/footer %]
654 The individual template components being included might look like these:
660 \& <h2>[% title %]</h2>
669 The \f(CW\*(C`WRAPPER\*(C'\fR directive provides a way of simplifying this a little. It
670 encloses a block up to a matching \f(CW\*(C`END\*(C'\fR directive, which is first processed
671 to generate some output. This is then passed to the named template file or
672 \&\f(CW\*(C`BLOCK\*(C'\fR as the \f(CW\*(C`content\*(C'\fR variable.
675 \& [% WRAPPER section
676 \& title = 'Quantum Mechanics'
678 \& Quantum mechanics is a very interesting subject wish
679 \& should prove easy for the layman to fully comprehend.
684 \& [% WRAPPER section
685 \& title = 'Desktop Nuclear Fusion for under $50'
687 \& This describes a simple device which generates significant
688 \& sustainable electrical power from common tap water by process
689 \& of nuclear fusion.
693 The single 'section' template can then be defined as:
696 \& <h2>[% title %]</h2>
702 Like other block directives, it can be used in side-effect notation:
705 \& [% INSERT legalese.txt WRAPPER big_bold_table %]
708 It's also possible to specify multiple templates to a \f(CW\*(C`WRAPPER\*(C'\fR directive.
709 The specification order indicates outermost to innermost wrapper templates.
710 For example, given the following template block definitions:
713 \& [% BLOCK bold %]<b>[% content %]</b>[% END %]
714 \& [% BLOCK italic %]<i>[% content %]</i>[% END %]
720 \& [% WRAPPER bold+italic %]Hello World[% END %]
723 would generate the following output:
726 \& <b><i>Hello World</i></b>
729 .IX Subsection "BLOCK"
730 The \f(CW\*(C`BLOCK\*(C'\fR...\f(CW\*(C`END\*(C'\fR construct can be used to define template component
731 blocks which can be processed with the \f(CW\*(C`INCLUDE\*(C'\fR, \f(CW\*(C`PROCESS\*(C'\fR and \f(CW\*(C`WRAPPER\*(C'\fR
735 \& [% BLOCK tabrow %]
737 \& <td>[% name %]<td>
738 \& <td>[% email %]</td>
745 \& [% PROCESS tabrow name='Fred' email='fred@nowhere.com' %]
746 \& [% PROCESS tabrow name='Alan' email='alan@nowhere.com' %]
750 A \f(CW\*(C`BLOCK\*(C'\fR definition can be used before it is defined, as long as the
751 definition resides in the same file. The block definition itself does
752 not generate any output.
755 \& [% PROCESS tmpblk %]
759 \& [% BLOCK tmpblk %] This is OK [% END %]
762 You can use an anonymous \f(CW\*(C`BLOCK\*(C'\fR to capture the output of a template
766 \& [% julius = BLOCK %]
767 \& And Caesar's spirit, ranging for revenge,
768 \& With Ate by his side come hot from hell,
769 \& Shall in these confines with a monarch's voice
770 \& Cry 'Havoc', and let slip the dogs of war;
771 \& That this foul deed shall smell above the earth
772 \& With carrion men, groaning for burial.
776 Like a named block, it can contain any other template directives which
777 are processed when the block is defined. The output generated by the
778 block is then assigned to the variable \f(CW\*(C`julius\*(C'\fR.
780 Anonymous \f(CW\*(C`BLOCK\*(C'\fRs can also be used to define block macros. The
781 enclosing block is processed each time the macro is called.
784 \& [% MACRO locate BLOCK %]
785 \& The [% animal %] sat on the [% place %].
790 \& [% locate(animal='cat', place='mat') %] # The cat sat on the mat
791 \& [% locate(animal='dog', place='log') %] # The dog sat on the log
793 .SH "Conditional Processing"
794 .IX Header "Conditional Processing"
795 .Sh "\s-1IF\s0 / \s-1UNLESS\s0 / \s-1ELSIF\s0 / \s-1ELSE\s0"
796 .IX Subsection "IF / UNLESS / ELSIF / ELSE"
797 The \f(CW\*(C`IF\*(C'\fR and \f(CW\*(C`UNLESS\*(C'\fR directives can be used to process or ignore a
798 block based on some run-time condition.
802 \& [% INCLUDE frameset %]
807 \& [% UNLESS text_mode %]
808 \& [% INCLUDE biglogo %]
812 Multiple conditions may be joined with \f(CW\*(C`ELSIF\*(C'\fR and/or \f(CW\*(C`ELSE\*(C'\fR blocks.
816 \& Hello [% name %], does your mother know you're
817 \& using her AOL account?
818 \& [% ELSIF age < 18 %]
819 \& Sorry, you're not old enough to enter
820 \& (and too dumb to lie about your age)
822 \& Welcome [% name %].
826 The following conditional and boolean operators may be used:
829 \& == != < <= > >= && || ! and or not
832 Conditions may be arbitrarily complex and are evaluated with the same
833 precedence as in Perl. Parenthesis may be used to explicitly
834 determine evaluation order.
837 \& # ridiculously contrived complex example
838 \& [% IF (name == 'admin' || uid <= 0) && mode == 'debug' %]
840 \& [% ELSIF more > less %]
841 \& That's more or less correct.
845 The \f(CW\*(C`and\*(C'\fR, \f(CW\*(C`or\*(C'\fR and \f(CW\*(C`not\*(C'\fR operator are provided as aliases for
846 \&\f(CW\*(C`&&\*(C'\fR, \f(CW\*(C`||\*(C'\fR and \f(CW\*(C`!\*(C'\fR, respectively. Unlike Perl, which treats
847 \&\f(CW\*(C`and\*(C'\fR, \f(CW\*(C`or\*(C'\fR and \f(CW\*(C`not\*(C'\fR as separate, lower-precedence versions of the
848 other operators, the Template Toolkit performs a straightforward substitution
849 of \f(CW\*(C`and\*(C'\fR for \f(CW\*(C`&&\*(C'\fR, and so on. That means that \f(CW\*(C`and\*(C'\fR, \f(CW\*(C`or\*(C'\fR and \f(CW\*(C`not\*(C'\fR
850 have the same operator precedence as \f(CW\*(C`&&\*(C'\fR, \f(CW\*(C`||\*(C'\fR and \f(CW\*(C`!\*(C'\fR.
851 .Sh "\s-1SWITCH\s0 / \s-1CASE\s0"
852 .IX Subsection "SWITCH / CASE"
853 The \f(CW\*(C`SWITCH\*(C'\fR / \f(CW\*(C`CASE\*(C'\fR construct can be used to perform a multi-way
854 conditional test. The \f(CW\*(C`SWITCH\*(C'\fR directive expects an expression which is
855 first evaluated and then compared against each \s-1CASE\s0 statement in turn.
856 Each \f(CW\*(C`CASE\*(C'\fR directive should contain a single value or a list of values
857 which should match. \f(CW\*(C`CASE\*(C'\fR may also be left blank or written as
858 \&\f(CW\*(C`[% CASE DEFAULT %]\*(C'\fR to specify a default match. Only one \f(CW\*(C`CASE\*(C'\fR matches,
859 there is no drop-through between \f(CW\*(C`CASE\*(C'\fR statements.
862 \& [% SWITCH myvar %]
863 \& [% CASE 'value1' %]
865 \& [% CASE ['value2', 'value3'] %] # multiple values
867 \& [% CASE myhash.keys %] # ditto
869 \& [% CASE %] # default
873 .SH "Loop Processing"
874 .IX Header "Loop Processing"
876 .IX Subsection "FOREACH"
877 The \f(CW\*(C`FOREACH\*(C'\fR directive will iterate through the items in a list, processing
878 the enclosed block for each one.
882 \& items = [ 'one', 'two', 'three' ]
888 \& [% FOREACH thing IN [ foo 'Bar' "$foo Baz" ] %]
895 \& [% FOREACH i IN items %]
902 \& [% stuff = [ foo "$foo Bar" ] %]
903 \& [% FOREACH s IN stuff %]
930 You can use also use \f(CW\*(C`=\*(C'\fR instead of \f(CW\*(C`IN\*(C'\fR if you prefer.
933 \& [% FOREACH i = items %]
936 When the \f(CW\*(C`FOREACH\*(C'\fR directive is used without specifying a target variable,
937 any iterated values which are hash references will be automatically
942 \& { id => 'tom', name => 'Thomas' },
943 \& { id => 'dick', name => 'Richard' },
944 \& { id => 'larry', name => 'Lawrence' },
950 \& [% FOREACH user IN userlist %]
951 \& [% user.id %] [% user.name %]
958 \& [% FOREACH userlist %]
959 \& [% id %] [% name %]
963 Note that this particular usage creates a localised variable context
964 to prevent the imported hash keys from overwriting any existing
965 variables. The imported definitions and any other variables defined
966 in such a \f(CW\*(C`FOREACH\*(C'\fR loop will be lost at the end of the loop, when the
967 previous context and variable values are restored.
969 However, under normal operation, the loop variable remains in scope
970 after the \f(CW\*(C`FOREACH\*(C'\fR loop has ended (caveat: overwriting any variable
971 previously in scope). This is useful as the loop variable is secretly
972 an iterator object (see below) and can be used to analyse the last
973 entry processed by the loop.
975 The \f(CW\*(C`FOREACH\*(C'\fR directive can also be used to iterate through the entries
976 in a hash array. Each entry in the hash is returned in sorted order
977 (based on the key) as a hash array containing 'key' and 'value' items.
982 \& dick => 'Richard',
983 \& larry => 'Lawrence',
989 \& [% FOREACH u IN users %]
990 \& * [% u.key %] : [% u.value %]
998 \& * larry : Lawrence
1002 The \f(CW\*(C`NEXT\*(C'\fR directive starts the next iteration in the \f(CW\*(C`FOREACH\*(C'\fR loop.
1005 \& [% FOREACH user IN userlist %]
1006 \& [% NEXT IF user.isguest %]
1007 \& Name: [% user.name %] Email: [% user.email %]
1011 The \f(CW\*(C`LAST\*(C'\fR directive can be used to prematurely exit the loop. \f(CW\*(C`BREAK\*(C'\fR is
1012 also provided as an alias for \f(CW\*(C`LAST\*(C'\fR.
1015 \& [% FOREACH match IN results.nsort('score').reverse %]
1016 \& [% LAST IF match.score < 50 %]
1017 \& [% match.score %] : [% match.url %]
1021 The \f(CW\*(C`FOREACH\*(C'\fR directive is implemented using the Template::Iterator
1022 module. A reference to the iterator object for a \f(CW\*(C`FOREACH\*(C'\fR directive is
1023 implicitly available in the \f(CW\*(C`loop\*(C'\fR variable. The following methods
1024 can be called on the \f(CW\*(C`loop\*(C'\fR iterator.
1027 \& size() number of elements in the list
1028 \& max() index number of last element (size \- 1)
1029 \& index() index of current iteration from 0 to max()
1030 \& count() iteration counter from 1 to size() (i.e. index() + 1)
1031 \& first() true if the current iteration is the first
1032 \& last() true if the current iteration is the last
1033 \& prev() return the previous item in the list
1034 \& next() return the next item in the list
1037 See Template::Iterator for further details.
1042 \& [% FOREACH item IN [ 'foo', 'bar', 'baz' ] \-%]
1043 \& [%\- "<ul>\en" IF loop.first %]
1044 \& <li>[% loop.count %]/[% loop.size %]: [% item %]
1045 \& [%\- "</ul>\en" IF loop.last %]
1059 Nested loops will work as expected, with the \f(CW\*(C`loop\*(C'\fR variable correctly
1060 referencing the innermost loop and being restored to any previous
1061 value (i.e. an outer loop) at the end of the loop.
1064 \& [% FOREACH group IN grouplist;
1065 \& # loop => group iterator
1066 \& "Groups:\en" IF loop.first;
1070 \& FOREACH user IN group.userlist;
1071 \& # loop => user iterator
1072 \& "$loop.count: $user.name\en";
1077 \& # loop => group iterator
1078 \& "End of Groups\en" IF loop.last;
1083 The \f(CW\*(C`iterator\*(C'\fR plugin can also be used to explicitly create an
1084 iterator object. This can be useful within nested loops where you
1085 need to keep a reference to the outer iterator within the inner loop.
1086 The iterator plugin effectively allows you to create an iterator by a
1087 name other than \f(CW\*(C`loop\*(C'\fR. See Template::Plugin::Iterator for further
1091 \& [% USE giter = iterator(grouplist) %]
1095 \& [% FOREACH group IN giter %]
1096 \& [% FOREACH user IN group.userlist %]
1097 \& user #[% loop.count %] in
1098 \& group [% giter.count %] is
1099 \& named [% user.name %]
1104 .IX Subsection "WHILE"
1105 The \f(CW\*(C`WHILE\*(C'\fR directive can be used to repeatedly process a template block
1106 while a conditional expression evaluates true. The expression may
1107 be arbitrarily complex as per \f(CW\*(C`IF\*(C'\fR / \f(CW\*(C`UNLESS\*(C'\fR.
1110 \& [% WHILE total < 100 %]
1112 \& [% total = calculate_new_total %]
1116 An assignment can be enclosed in parenthesis to evaluate the assigned
1120 \& [% WHILE (user = get_next_user_record) %]
1125 The \f(CW\*(C`NEXT\*(C'\fR directive can be used to start the next iteration of a
1126 \&\f(CW\*(C`WHILE\*(C'\fR loop and \f(CW\*(C`BREAK\*(C'\fR can be used to exit the loop, both as per \f(CW\*(C`FOREACH\*(C'\fR.
1128 The Template Toolkit uses a failsafe counter to prevent runaway \f(CW\*(C`WHILE\*(C'\fR
1129 loops which would otherwise never terminate. If the loop exceeds 1000
1130 iterations then an \f(CW\*(C`undef\*(C'\fR exception will be thrown, reporting the
1134 \& WHILE loop terminated (> 1000 iterations)
1137 The \f(CW$Template::Directive::WHILE_MAX\fR variable controls this behaviour
1138 and can be set to a higher value if necessary.
1139 .SH "Filters, Plugins, Macros and Perl"
1140 .IX Header "Filters, Plugins, Macros and Perl"
1142 .IX Subsection "FILTER"
1143 The \f(CW\*(C`FILTER\*(C'\fR directive can be used to post-process the output of a
1144 block. A number of standard filters are provided with the Template
1145 Toolkit. The \f(CW\*(C`html\*(C'\fR filter, for example, escapes the '<', '>'
1146 and '&' characters to prevent them from being interpreted as \s-1HTML\s0 tags
1147 or entity reference markers.
1150 \& [% FILTER html %]
1151 \& HTML text may have < and > characters embedded
1152 \& which you want converted to the correct HTML entities.
1159 \& HTML text may have < and > characters embedded
1160 \& which you want converted to the correct HTML entities.
1163 The \f(CW\*(C`FILTER\*(C'\fR directive can also follow various other non-block directives.
1167 \& [% INCLUDE mytext FILTER html %]
1170 The \f(CW\*(C`|\*(C'\fR character can also be used as an alias for \f(CW\*(C`FILTER\*(C'\fR.
1173 \& [% INCLUDE mytext | html %]
1176 Multiple filters can be chained together and will be called in sequence.
1179 \& [% INCLUDE mytext FILTER html FILTER html_para %]
1185 \& [% INCLUDE mytext | html | html_para %]
1188 Filters come in two flavours, known as 'static' or 'dynamic'. A
1189 static filter is a simple subroutine which accepts a text string as
1190 the only argument and returns the modified text. The \f(CW\*(C`html\*(C'\fR filter is
1191 an example of a static filter, implemented as:
1194 \& sub html_filter {
1195 \& my $text = shift;
1205 Dynamic filters can accept arguments which are specified when the filter
1206 is called from a template. The \f(CW\*(C`repeat\*(C'\fR filter is such an example,
1207 accepting a numerical argument which specifies the number of times
1208 that the input text should be repeated.
1211 \& [% FILTER repeat(3) %]blah [% END %]
1220 These are implemented as filter 'factories'. The factory subroutine
1221 is passed a reference to the current Template::Context object along
1222 with any additional arguments specified. It should then return a
1223 subroutine reference (e.g. a closure) which implements the filter.
1224 The \f(CW\*(C`repeat\*(C'\fR filter factory is implemented like this:
1227 \& sub repeat_filter_factory {
1228 \& my ($context, $iter) = @_;
1229 \& $iter = 1 unless defined $iter;
1234 \& my $text = shift;
1235 \& $text = '' unless defined $text;
1236 \& return join('\en', $text) x $iter;
1241 The \f(CW\*(C`FILTERS\*(C'\fR option, described in Template::Manual::Config, allows custom
1242 filters to be defined when a Template object is instantiated. The
1243 \&\fIdefine_filter()\fR method allows further
1244 filters to be defined at any time.
1246 When using a filter, it is possible to assign an alias to it for
1247 further use. This is most useful for dynamic filters that you want
1248 to re-use with the same configuration.
1251 \& [% FILTER echo = repeat(2) %]
1252 \& Is there anybody out there?
1257 \& [% FILTER echo %]
1258 \& Mother, should I build a wall?
1265 \& Is there anybody out there?
1266 \& Is there anybody out there?
1270 \& Mother, should I build a wall?
1271 \& Mother, should I build a wall?
1274 The \f(CW\*(C`FILTER\*(C'\fR directive automatically quotes the name of the filter. As
1275 with \f(CW\*(C`INCLUDE\*(C'\fR et al, you can use a variable to provide the name of the
1276 filter, prefixed by \f(CW\*(C`$\*(C'\fR.
1279 \& [% myfilter = 'html' %]
1280 \& [% FILTER $myfilter %] # same as [% FILTER html %]
1285 A template variable can also be used to define a static filter
1286 subroutine. However, the Template Toolkit will automatically call any
1287 subroutine bound to a variable and use the value returned. Thus, the
1288 above example could be implemented as:
1292 \& myfilter => sub { return 'html' },
1299 \& [% FILTER $myfilter %] # same as [% FILTER html %]
1304 To define a template variable that evaluates to a subroutine reference
1305 that can be used by the \f(CW\*(C`FILTER\*(C'\fR directive, you should create a
1306 subroutine that, when called automatically by the Template Toolkit,
1307 returns another subroutine reference which can then be used to perform
1308 the filter operation. Note that only static filters can be
1309 implemented in this way.
1313 \& myfilter => sub { \e&my_filter_sub },
1318 \& sub my_filter_sub {
1319 \& my $text = shift;
1328 \& [% FILTER $myfilter %]
1333 Alternately, you can bless a subroutine reference into a class (any
1334 class will do) to fool the Template Toolkit into thinking it's an
1335 object rather than a subroutine. This will then bypass the automatic
1336 \&\*(L"call\-a\-subroutine\-to\-return\-a\-value\*(R" magic.
1340 \& myfilter => bless(\e&my_filter_sub, 'anything_you_like'),
1347 \& [% FILTER $myfilter %]
1352 Filters bound to template variables remain local to the variable context in
1353 which they are defined. That is, if you define a filter in a \f(CW\*(C`PERL\*(C'\fR block
1354 within a template that is loaded via \f(CW\*(C`INCLUDE\*(C'\fR, then the filter definition
1355 will only exist until the end of that template when the stash is delocalised,
1356 restoring the previous variable state. If you want to define a filter which
1357 persists for the lifetime of the processor, or define additional dynamic
1358 filter factories, then you can call the
1359 \&\fIdefine_filter()\fR method on the current
1360 Template::Context object.
1362 See Template::Manual::Filters for a complete list of available filters,
1363 their descriptions and examples of use.
1365 .IX Subsection "USE"
1366 The \f(CW\*(C`USE\*(C'\fR directive can be used to load and initialise \*(L"plugin\*(R"
1370 \& [% USE myplugin %]
1373 A plugin is a regular Perl module that conforms to a particular
1374 object-oriented interface, allowing it to be loaded into and used
1375 automatically by the Template Toolkit. For details of this interface
1376 and information on writing plugins, consult Template::Plugin.
1378 A number of standard plugins are included with the Template Toolkit
1379 (see below and Template::Manual::Plugins). The names of these
1380 standard plugins are case insensitive.
1383 \& [% USE CGI %] # => Template::Plugin::CGI
1384 \& [% USE Cgi %] # => Template::Plugin::CGI
1385 \& [% USE cgi %] # => Template::Plugin::CGI
1388 You can also define further plugins using the \f(CW\*(C`PLUGINS\*(C'\fR option.
1391 \& my $tt = Template\->new({
1393 \& foo => 'My::Plugin::Foo',
1394 \& bar => 'My::Plugin::Bar',
1399 The recommended convention is to specify these plugin names in lower
1400 case. The Template Toolkit first looks for an exact case-sensitive
1401 match and then tries the lower case conversion of the name specified.
1404 \& [% USE Foo %] # look for 'Foo' then 'foo'
1407 If you define all your \f(CW\*(C`PLUGINS\*(C'\fR with lower case names then they will be
1408 located regardless of how the user specifies the name in the \f(CW\*(C`USE\*(C'\fR
1409 directive. If, on the other hand, you define your \f(CW\*(C`PLUGINS\*(C'\fR with upper
1410 or mixed case names then the name specified in the \f(CW\*(C`USE\*(C'\fR directive must
1411 match the case exactly.
1413 If the plugin isn't defined in either the standard plugins
1414 (\f(CW$Template::Plugins::STD_PLUGINS\fR) or via the \f(CW\*(C`PLUGINS\*(C'\fR option, then
1415 the \f(CW\*(C`PLUGIN_BASE\*(C'\fR is searched.
1417 In this case the plugin name \fIis\fR case\-sensitive. It is appended to
1418 each of the \f(CW\*(C`PLUGIN_BASE\*(C'\fR module namespaces in turn (default:
1419 \&\f(CW\*(C`Template::Plugin\*(C'\fR) to construct a full module name which it attempts
1420 to locate and load. Any periods, '\f(CW\*(C`.\*(C'\fR', in the name will be converted
1421 to '\f(CW\*(C`::\*(C'\fR'.
1424 \& [% USE MyPlugin %] # => Template::Plugin::MyPlugin
1425 \& [% USE Foo.Bar %] # => Template::Plugin::Foo::Bar
1428 The \f(CW\*(C`LOAD_PERL\*(C'\fR option (disabled by default) provides a further way by
1429 which external Perl modules may be loaded. If a regular Perl module
1430 (i.e. not a \f(CW\*(C`Template::Plugin::*\*(C'\fR or other module relative to some
1431 \&\f(CW\*(C`PLUGIN_BASE\*(C'\fR) supports an object-oriented interface and a \f(CW\*(C`new()\*(C'\fR
1432 constructor then it can be loaded and instantiated automatically. The
1433 following trivial example shows how the IO::File module might be used.
1436 \& [% USE file = IO.File('/tmp/mydata') %]
1440 \& [% WHILE (line = file.getline) %]
1441 \& <!\-\- [% line %] \-\->
1445 Any additional parameters supplied in parenthesis after the plugin
1446 name will be also be passed to the \f(CW\*(C`new()\*(C'\fR constructor. A reference to
1447 the current Template::Context object is passed as the first
1451 \& [% USE MyPlugin('foo', 123) %]
1457 \& Template::Plugin::MyPlugin\->new($context, 'foo', 123);
1460 The only exception to this is when a module is loaded via the
1461 \&\f(CW\*(C`LOAD_PERL\*(C'\fR option. In this case the \f(CW$context\fR reference is \fInot\fR
1462 passed to the \f(CW\*(C`new()\*(C'\fR constructor. This is based on the assumption that
1463 the module is a regular Perl module rather than a Template Toolkit
1464 plugin so isn't expecting a context reference and wouldn't know what
1465 to do with it anyway.
1467 Named parameters may also be specified. These are collated into a
1468 hash which is passed by reference as the last parameter to the
1469 constructor, as per the general code calling interface.
1472 \& [% USE url('/cgi\-bin/foo', mode='submit', debug=1) %]
1478 \& Template::Plugin::URL\->new(
1481 \& { mode => 'submit', debug => 1 }
1485 The plugin may represent any data type; a simple variable, hash, list or
1486 code reference, but in the general case it will be an object reference.
1487 Methods can be called on the object (or the relevant members of the
1488 specific data type) in the usual way:
1491 \& [% USE table(mydata, rows=3) %]
1495 \& [% FOREACH row IN table.rows %]
1497 \& [% FOREACH item IN row %]
1498 \& <td>[% item %]</td>
1504 An alternative name may be provided for the plugin by which it can be
1508 \& [% USE scores = table(myscores, cols=5) %]
1512 \& [% FOREACH row IN scores.rows %]
1517 You can use this approach to create multiple plugin objects with
1518 different configurations. This example shows how the
1519 format plugin is used to create
1520 sub-routines bound to variables for formatting text as per \f(CW\*(C`printf()\*(C'\fR.
1523 \& [% USE bold = format('<b>%s</b>') %]
1524 \& [% USE ital = format('<i>%s</i>') %]
1525 \& [% bold('This is bold') %]
1526 \& [% ital('This is italic') %]
1532 \& <b>This is bold</b>
1533 \& <i>This is italic</i>
1536 This next example shows how the \s-1URL\s0 plugin can be
1537 used to build dynamic URLs from a base part and optional query parameters.
1540 \& [% USE mycgi = URL('/cgi\-bin/foo.pl', debug=1) %]
1541 \& <a href="[% mycgi %]">...
1542 \& <a href="[% mycgi(mode='submit') %]"...
1548 \& <a href="/cgi\-bin/foo.pl?debug=1">...
1549 \& <a href="/cgi\-bin/foo.pl?mode=submit&debug=1">...
1552 The \s-1CGI\s0 plugin is an example of one which delegates
1553 to another Perl module. In this this case, to Lincoln Stein's \f(CW\*(C`CGI\*(C'\fR module.
1554 All of the methods provided by the \f(CW\*(C`CGI\*(C'\fR module are available via the plugin.
1559 \& CGI.checkbox_group( name = 'colours',
1560 \& values = [ 'red' 'green' 'blue' ] );
1561 \& CGI.popup_menu( name = 'items',
1562 \& values = [ 'foo' 'bar' 'baz' ] );
1567 See Template::Manual::Plugins for more information on the plugins
1568 distributed with the toolkit or available from \s-1CPAN\s0.
1570 .IX Subsection "MACRO"
1571 The \f(CW\*(C`MACRO\*(C'\fR directive allows you to define a directive or directive block
1572 which is then evaluated each time the macro is called.
1575 \& [% MACRO header INCLUDE header %]
1578 Calling the macro as:
1584 is then equivalent to:
1587 \& [% INCLUDE header %]
1590 Macros can be passed named parameters when called. These values remain
1594 \& [% header(title='Hello World') %]
1600 \& [% INCLUDE header title='Hello World' %]
1603 A \f(CW\*(C`MACRO\*(C'\fR definition may include parameter names. Values passed to the
1604 macros are then mapped to these local variables. Other named parameters
1608 \& [% MACRO header(title) INCLUDE header %]
1609 \& [% header('Hello World') %]
1610 \& [% header('Hello World', bgcol='#123456') %]
1616 \& [% INCLUDE header title='Hello World' %]
1617 \& [% INCLUDE header title='Hello World' bgcol='#123456' %]
1620 Here's another example, defining a macro for display numbers
1621 in comma-delimited groups of 3, using the chunk and join virtual
1625 \& [% MACRO number(n) GET n.chunk(\-3).join(',') %]
1626 \& [% number(1234567) %] # 1,234,567
1629 A \f(CW\*(C`MACRO\*(C'\fR may precede any directive and must conform to the structure
1633 \& [% MACRO header IF frames %]
1634 \& [% INCLUDE frames/header %]
1636 \& [% INCLUDE header %]
1644 A \f(CW\*(C`MACRO\*(C'\fR may also be defined as an anonymous \f(CW\*(C`BLOCK\*(C'\fR. The block will be
1645 evaluated each time the macro is called.
1648 \& [% MACRO header BLOCK %]
1657 If you've got the \f(CW\*(C`EVAL_PERL\*(C'\fR option set, then you can even define a
1658 \&\f(CW\*(C`MACRO\*(C'\fR as a \f(CW\*(C`PERL\*(C'\fR block (see below):
1661 \& [% MACRO triple(n) PERL %]
1662 \& my $n = $stash\->get('n');
1667 .IX Subsection "PERL"
1668 (for the advanced reader)
1670 The \f(CW\*(C`PERL\*(C'\fR directive is used to mark the start of a block which contains
1671 Perl code for evaluation. The \f(CW\*(C`EVAL_PERL\*(C'\fR option must be enabled for Perl
1672 code to be evaluated or a \f(CW\*(C`perl\*(C'\fR exception will be thrown with the
1673 message '\f(CW\*(C`EVAL_PERL not set\*(C'\fR'.
1675 Perl code is evaluated in the \f(CW\*(C`Template::Perl\*(C'\fR package. The \f(CW$context\fR
1676 package variable contains a reference to the current Template::Context
1677 object. This can be used to access the functionality of the Template
1678 Toolkit to process other templates, load plugins, filters, etc.
1679 See Template::Context for further details.
1683 \& print $context\->include('myfile');
1687 The $stash variable contains a reference to the top-level stash object
1688 which manages template variables. Through this, variable values can
1689 be retrieved and updated. See Template::Stash for further details.
1693 \& $stash\->set(foo => 'bar');
1694 \& print "foo value: ", $stash\->get('foo');
1704 Output is generated from the \f(CW\*(C`PERL\*(C'\fR block by calling \f(CW\*(C`print()\*(C'\fR. Note that
1705 the \f(CW\*(C`Template::Perl::PERLOUT\*(C'\fR handle is selected (tied to an output
1706 buffer) instead of \f(CW\*(C`STDOUT\*(C'\fR.
1710 \& print "foo\en"; # OK
1711 \& print PERLOUT "bar\en"; # OK, same as above
1712 \& print Template::Perl::PERLOUT "baz\en"; # OK, same as above
1713 \& print STDOUT "qux\en"; # WRONG!
1717 The \f(CW\*(C`PERL\*(C'\fR block may contain other template directives. These are
1718 processed before the Perl code is evaluated.
1721 \& [% name = 'Fred Smith' %]
1726 \& print "[% name %]\en";
1730 Thus, the Perl code in the above example is evaluated as:
1733 \& print "Fred Smith\en";
1736 Exceptions may be thrown from within \f(CW\*(C`PERL\*(C'\fR blocks using \f(CW\*(C`die()\*(C'\fR.
1737 They will be correctly caught by enclosing \f(CW\*(C`TRY\*(C'\fR blocks.
1742 \& die "nothing to live for\en";
1745 \& error: [% error.info %]
1750 error: nothing to live for
1751 .Sh "\s-1RAWPERL\s0"
1752 .IX Subsection "RAWPERL"
1753 (for the very advanced reader)
1755 The Template Toolkit parser reads a source template and generates the
1756 text of a Perl subroutine as output. It then uses \f(CW\*(C`eval()\*(C'\fR to evaluate
1757 it into a subroutine reference. This subroutine is then called to
1758 process the template, passing a reference to the current
1759 Template::Context object through which the functionality of the
1760 Template Toolkit can be accessed. The subroutine reference can be
1761 cached, allowing the template to be processed repeatedly without
1762 requiring any further parsing.
1764 For example, a template such as:
1767 \& [% PROCESS header %]
1768 \& The [% animal %] sat on the [% location %]
1769 \& [% PROCESS footer %]
1772 is converted into the following Perl subroutine definition:
1776 \& my $context = shift;
1777 \& my $stash = $context\->stash;
1784 \& $output .= $context\->process('header');
1785 \& $output .= "The ";
1786 \& $output .= $stash\->get('animal');
1787 \& $output .= " sat on the ";
1788 \& $output .= $stash\->get('location');
1789 \& $output .= $context\->process('footer');
1790 \& $output .= "\en";
1793 \& $error = $context\->catch($@, \e$output);
1794 \& die $error unless $error\->type eq 'return';
1803 To examine the Perl code generated, such as in the above example, set
1804 the \f(CW$Template::Parser::DEBUG\fR package variable to any true value. You
1805 can also set the \f(CW$Template::Directive::PRETTY\fR variable true to have
1806 the code formatted in a readable manner for human consumption. The
1807 source code for each generated template subroutine will be printed to
1808 \&\f(CW\*(C`STDERR\*(C'\fR on compilation (i.e. the first time a template is used).
1811 \& $Template::Parser::DEBUG = 1;
1812 \& $Template::Directive::PRETTY = 1;
1816 \& $template\->process($file, $vars)
1817 \& || die $template\->error(), "\en";
1820 The \f(CW\*(C`PERL\*(C'\fR ... \f(CW\*(C`END\*(C'\fR construct allows Perl code to be embedded into a
1821 template when the \f(CW\*(C`EVAL_PERL\*(C'\fR option is set. It is evaluated at
1822 \&\*(L"runtime\*(R" using \f(CW\*(C`eval()\*(C'\fR each time the template subroutine is called.
1823 This is inherently flexible, but not as efficient as it could be,
1824 especially in a persistent server environment where a template may be
1825 processed many times.
1827 The \f(CW\*(C`RAWPERL\*(C'\fR directive allows you to write Perl code that is integrated
1828 directly into the generated Perl subroutine text. It is evaluated
1829 once at compile time and is stored in cached form as part of the
1830 compiled template subroutine. This makes \f(CW\*(C`RAWPERL\*(C'\fR blocks more
1831 efficient than \f(CW\*(C`PERL\*(C'\fR blocks.
1833 The downside is that you must code much closer to the metal. For example, in a
1834 \&\f(CW\*(C`PERL\*(C'\fR block you can call \fIprint()\fR to generate some output. \f(CW\*(C`RAWPERL\*(C'\fR
1835 blocks don't afford such luxury. The code is inserted directly into the
1836 generated subroutine text and should conform to the convention of appending to
1837 the \f(CW$output\fR variable.
1840 \& [% PROCESS header %]
1845 \& $output .= "Some output\en";
1847 \& $output .= "Some more output\en";
1851 The critical section of the generated subroutine for this example would
1852 then look something like:
1857 \& $output .= $context\->process('header');
1858 \& $output .= "\en";
1859 \& $output .= "Some output\en";
1861 \& $output .= "Some more output\en";
1862 \& $output .= "\en";
1867 As with \f(CW\*(C`PERL\*(C'\fR blocks, the $context and
1868 $stash references are pre-defined and available for use
1869 within \f(CW\*(C`RAWPERL\*(C'\fR code.
1870 .SH "Exception Handling and Flow Control"
1871 .IX Header "Exception Handling and Flow Control"
1872 .Sh "\s-1TRY\s0 / \s-1THROW\s0 / \s-1CATCH\s0 / \s-1FINAL\s0"
1873 .IX Subsection "TRY / THROW / CATCH / FINAL"
1874 (more advanced material)
1876 The Template Toolkit supports fully functional, nested exception
1877 handling. The \f(CW\*(C`TRY\*(C'\fR directive introduces an exception handling scope
1878 which continues until the matching \f(CW\*(C`END\*(C'\fR directive. Any errors that
1879 occur within that block will be caught and can be handled by one
1880 of the \f(CW\*(C`CATCH\*(C'\fR blocks defined.
1884 \& ...blah...blah...
1885 \& [% CALL somecode %]
1887 \& [% INCLUDE someblock %]
1890 \& An error occurred!
1894 Errors are raised as exceptions (objects of the Template::Exception class)
1895 which contain two fields: \f(CW\*(C`type\*(C'\fR and \f(CW\*(C`info\*(C'\fR. The exception \f(CW\*(C`type\*(C'\fR is used
1896 to indicate the kind of error that occurred. It is a simple text string which
1897 can contain letters, numbers, '\f(CW\*(C`_\*(C'\fR' or '\f(CW\*(C`.\*(C'\fR'. The \f(CW\*(C`info\*(C'\fR field contains an
1898 error message indicating what actually went wrong. Within a catch block, the
1899 exception object is aliased to the \f(CW\*(C`error\*(C'\fR variable. You can access the \f(CW\*(C`type\*(C'\fR
1900 and \f(CW\*(C`info\*(C'\fR fields directly.
1903 \& [% mydsn = 'dbi:MySQL:foobar' %]
1909 \& [% USE DBI(mydsn) %]
1911 \& ERROR! Type: [% error.type %]
1912 \& Info: [% error.info %]
1916 output (assuming a non-existant database called '\f(CW\*(C`foobar\*(C'\fR'):
1920 \& Info: Unknown database "foobar"
1923 The \f(CW\*(C`error\*(C'\fR variable can also be specified by itself and will return a
1924 string of the form "\f(CW\*(C`$type error \- $info\*(C'\fR".
1929 \& ERROR: [% error %]
1936 \& ERROR: DBI error \- Unknown database "foobar"
1939 Each \f(CW\*(C`CATCH\*(C'\fR block may be specified with a particular exception type
1940 denoting the kind of error that it should catch. Multiple \f(CW\*(C`CATCH\*(C'\fR
1941 blocks can be provided to handle different types of exception that may
1942 be thrown in the \f(CW\*(C`TRY\*(C'\fR block. A \f(CW\*(C`CATCH\*(C'\fR block specified without any type,
1943 as in the previous example, is a default handler which will catch any
1944 otherwise uncaught exceptions. This can also be specified as
1945 \&\f(CW\*(C`[% CATCH DEFAULT %]\*(C'\fR.
1949 \& [% INCLUDE myfile %]
1950 \& [% USE DBI(mydsn) %]
1951 \& [% CALL somecode %]
1953 \& File Error! [% error.info %]
1955 \& [% INCLUDE database/error.html %]
1961 Remember that you can specify multiple directives within a single tag,
1962 each delimited by '\f(CW\*(C`;\*(C'\fR'. So the above example can be written more
1971 \& "File Error! $error.info";
1973 \& INCLUDE database/error.html;
1980 The \f(CW\*(C`DBI\*(C'\fR plugin throws exceptions of the \f(CW\*(C`DBI\*(C'\fR type (in case that
1981 wasn't already obvious). The other specific exception caught here is
1982 of the \f(CW\*(C`file\*(C'\fR type.
1984 A \f(CW\*(C`file\*(C'\fR exception is automatically thrown by the Template Toolkit when it
1985 can't find a file, or fails to load, parse or process a file that has been
1986 requested by an \f(CW\*(C`INCLUDE\*(C'\fR, \f(CW\*(C`PROCESS\*(C'\fR, \f(CW\*(C`INSERT\*(C'\fR or \f(CW\*(C`WRAPPER\*(C'\fR directive.
1987 If \f(CW\*(C`myfile\*(C'\fR can't be found in the example above, the \f(CW\*(C`[% INCLUDE myfile %]\*(C'\fR
1988 directive will raise a \f(CW\*(C`file\*(C'\fR exception which is then caught by the
1989 \&\f(CW\*(C`[% CATCH file %]\*(C'\fR block. The output generated would be:
1992 \& File Error! myfile: not found
1995 Note that the \f(CW\*(C`DEFAULT\*(C'\fR option (disabled by default) allows you to specify a
1996 default file to be used any time a template file can't be found. This will
1997 prevent file exceptions from ever being raised when a non-existant file is
1998 requested (unless, of course, the \f(CW\*(C`DEFAULT\*(C'\fR file your specify doesn't exist).
1999 Errors encountered once the file has been found (i.e. read error, parse error)
2000 will be raised as file exceptions as per usual.
2002 Uncaught exceptions (i.e. if the \f(CW\*(C`TRY\*(C'\fR block doesn't have a type specific or
2003 default \f(CW\*(C`CATCH\*(C'\fR handler) may be caught by enclosing \f(CW\*(C`TRY\*(C'\fR blocks which can
2004 be nested indefinitely across multiple templates. If the error isn't caught at
2005 any level then processing will stop and the Template
2006 \&\fIprocess()\fR method will return a false value to the
2007 caller. The relevant Template::Exception object can be retrieved by calling
2008 the \fIerror()\fR method.
2014 \& [% INCLUDE $user.header %]
2016 \& [% INCLUDE header %]
2020 \& [% INCLUDE database/error.html %]
2024 In this example, the inner \f(CW\*(C`TRY\*(C'\fR block is used to ensure that the first
2025 \&\f(CW\*(C`INCLUDE\*(C'\fR directive works as expected. We're using a variable to
2026 provide the name of the template we want to include, \f(CW\*(C`user.header\*(C'\fR, and
2027 it's possible this contains the name of a non-existant template, or
2028 perhaps one containing invalid template directives. If the \f(CW\*(C`INCLUDE\*(C'\fR fails
2029 with a \f(CW\*(C`file\*(C'\fR error then we \f(CW\*(C`CATCH\*(C'\fR it in the inner block and \f(CW\*(C`INCLUDE\*(C'\fR
2030 the default \f(CW\*(C`header\*(C'\fR file instead. Any \f(CW\*(C`DBI\*(C'\fR errors that occur within
2031 the scope of the outer \f(CW\*(C`TRY\*(C'\fR block will be caught in the relevant \f(CW\*(C`CATCH\*(C'\fR
2032 block, causing the \f(CW\*(C`database/error.html\*(C'\fR template to be processed.
2033 Note that included templates inherit all currently defined template
2034 variable so these error files can quite happily access the <error>
2035 variable to retrieve information about the currently caught exception.
2036 For example, the \f(CW\*(C`database/error.html\*(C'\fR template might look like this:
2039 \& <h2>Database Error</h2>
2040 \& A database error has occurred: [% error.info %]
2043 You can also specify a \f(CW\*(C`FINAL\*(C'\fR block. This is always processed
2044 regardless of the outcome of the \f(CW\*(C`TRY\*(C'\fR and/or \f(CW\*(C`CATCH\*(C'\fR blocks. If an
2045 exception is uncaught then the \f(CW\*(C`FINAL\*(C'\fR block is processed before jumping
2046 to the enclosing block or returning to the caller.
2060 The output from the \f(CW\*(C`TRY\*(C'\fR block is left intact up to the point where an
2061 exception occurs. For example, this template:
2065 \& This gets printed
2066 \& [% THROW food 'carrots' %]
2069 \& culinary delights: [% error.info %]
2073 generates the following output:
2076 \& This gets printed
2077 \& culinary delights: carrots
2080 The \f(CW\*(C`CLEAR\*(C'\fR directive can be used in a \f(CW\*(C`CATCH\*(C'\fR or \f(CW\*(C`FINAL\*(C'\fR block to clear
2081 any output created in the \f(CW\*(C`TRY\*(C'\fR block.
2085 \& This gets printed
2086 \& [% THROW food 'carrots' %]
2090 \& culinary delights: [% error.info %]
2097 \& culinary delights: carrots
2100 Exception types are hierarchical, with each level being separated by
2101 the familiar dot operator. A \f(CW\*(C`DBI.connect\*(C'\fR exception is a more
2102 specific kind of \f(CW\*(C`DBI\*(C'\fR error. Similarly, an \f(CW\*(C`example.error.barf\*(C'\fR is a
2103 more specific kind of \f(CW\*(C`example.error\*(C'\fR type which itself is also a
2104 \&\f(CW\*(C`example\*(C'\fR error.
2106 A \f(CW\*(C`CATCH\*(C'\fR handler that specifies a general exception
2107 type (such as \f(CW\*(C`DBI\*(C'\fR or \f(CW\*(C`example.error\*(C'\fR) will also catch more specific
2108 types that have the same prefix as long as a more specific handler
2109 isn't defined. Note that the order in which \f(CW\*(C`CATCH\*(C'\fR handlers are
2110 defined is irrelevant; a more specific handler will always catch an
2111 exception in preference to a more generic or default one.
2117 \& INCLUDE database/error.html ;
2118 \& CATCH DBI.connect ;
2119 \& INCLUDE database/connect.html ;
2121 \& INCLUDE error.html ;
2126 In this example, a \f(CW\*(C`DBI.connect\*(C'\fR error has it's own handler, a more general
2127 \&\f(CW\*(C`DBI\*(C'\fR block is used for all other \f(CW\*(C`DBI\*(C'\fR or \f(CW\*(C`DBI.*\*(C'\fR errors and a default
2128 handler catches everything else.
2130 Exceptions can be raised in a template using the \f(CW\*(C`THROW\*(C'\fR directive. The
2131 first parameter is the exception type which doesn't need to be quoted
2132 (but can be, it's the same as \f(CW\*(C`INCLUDE\*(C'\fR) followed by the relevant error
2133 message which can be any regular value such as a quoted string,
2137 \& [% THROW food "Missing ingredients: $recipe.error" %]
2138 \& [% THROW user.login 'no user id: please login' %]
2139 \& [% THROW $myerror.type "My Error: $myerror.info" %]
2142 It's also possible to specify additional positional or named
2143 parameters to the \f(CW\*(C`THROW\*(C'\fR directive if you want to pass more than
2144 just a simple message back as the error info field.
2147 \& [% THROW food 'eggs' 'flour' msg='Missing Ingredients' %]
2150 In this case, the error \f(CW\*(C`info\*(C'\fR field will be a hash array containing the
2151 named arguments and an \f(CW\*(C`args\*(C'\fR item which contains a list of the positional
2157 \& msg => 'Missing Ingredients',
2158 \& args => ['eggs', 'flour'],
2162 In addition to specifying individual positional arguments as
2163 \&\f(CW\*(C`[% error.info.args.n %]\*(C'\fR, the \f(CW\*(C`info\*(C'\fR hash contains keys directly
2164 pointing to the positional arguments, as a convenient shortcut.
2167 \& [% error.info.0 %] # same as [% error.info.args.0 %]
2170 Exceptions can also be thrown from Perl code which you've bound to
2171 template variables, or defined as a plugin or other extension. To
2172 raise an exception, call \f(CW\*(C`die()\*(C'\fR passing a reference to a
2173 Template::Exception object as the argument. This will then be caught
2174 by any enclosing \f(CW\*(C`TRY\*(C'\fR blocks from where the code was called.
2177 \& use Template::Exception;
2181 \& # ... do something ...
2182 \& die Template::Exception\->new('myerr.naughty',
2183 \& 'Bad, bad error');
2194 \& "Error: $error" ;
2202 \& Error: myerr.naughty error \- Bad, bad error
2205 The \f(CW\*(C`info\*(C'\fR field can also be a reference to another object or data
2206 structure, if required.
2209 \& die Template::Exception\->new('myerror', {
2210 \& module => 'foo.pl',
2211 \& errors => [ 'bad permissions', 'naughty boy' ],
2215 Later, in a template:
2220 \& [% CATCH myerror %]
2221 \& [% error.info.errors.size or 'no';
2222 \& error.info.errors.size == 1 ? ' error' : ' errors' %]
2223 \& in [% error.info.module %]:
2224 \& [% error.info.errors.join(', ') %].
2228 Generating the output:
2231 \& 2 errors in foo.pl:
2232 \& bad permissions, naughty boy.
2235 You can also call \f(CW\*(C`die()\*(C'\fR with a single string, as is common in much
2236 existing Perl code. This will automatically be converted to an
2237 exception of the '\f(CW\*(C`undef\*(C'\fR' type (that's the literal string '\f(CW\*(C`undef\*(C'\fR',
2238 not the undefined value). If the string isn't terminated with a
2239 newline then Perl will append the familiar \f(CW" at $file line $line"\fR
2244 \& # ... do something ...
2245 \& die "I'm sorry, Dave, I can't do that\en";
2249 If you're writing a plugin, or some extension code that has the current
2250 Template::Context in scope (you can safely skip this section if this means
2251 nothing to you) then you can also raise an exception by calling the context
2252 \&\fIthrow()\fR method. You can pass it an
2253 Template::Exception object reference, a pair of \f(CW\*(C`($type, $info)\*(C'\fR
2254 parameters or just an \f(CW$info\fR string to create an exception of '\f(CW\*(C`undef\*(C'\fR' type.
2257 \& $context\->throw($e); # exception object
2258 \& $context\->throw('Denied'); # 'undef' type
2259 \& $context\->throw('user.passwd', 'Bad Password');
2262 .IX Subsection "NEXT"
2263 The \f(CW\*(C`NEXT\*(C'\fR directive can be used to start the next iteration of a \f(CW\*(C`FOREACH\*(C'\fR
2264 or \f(CW\*(C`WHILE\*(C'\fR loop.
2267 \& [% FOREACH user IN users %]
2268 \& [% NEXT IF user.isguest %]
2269 \& Name: [% user.name %] Email: [% user.email %]
2273 .IX Subsection "LAST"
2274 The \f(CW\*(C`LAST\*(C'\fR directive can be used to prematurely exit a \f(CW\*(C`FOREACH\*(C'\fR or \f(CW\*(C`WHILE\*(C'\fR
2278 \& [% FOREACH user IN users %]
2279 \& Name: [% user.name %] Email: [% user.email %]
2280 \& [% LAST IF some.condition %]
2284 \&\f(CW\*(C`BREAK\*(C'\fR can also be used as an alias for \f(CW\*(C`LAST\*(C'\fR.
2286 .IX Subsection "RETURN"
2287 The \f(CW\*(C`RETURN\*(C'\fR directive can be used to stop processing the current template
2288 and return to the template from which it was called, resuming processing at
2289 the point immediately after the \f(CW\*(C`INCLUDE\*(C'\fR, \f(CW\*(C`PROCESS\*(C'\fR or \f(CW\*(C`WRAPPER\*(C'\fR
2290 directive. If there is no enclosing template then the Template
2291 \&\fIprocess()\fR method will return to the calling code with a
2296 \& [% INCLUDE half_wit %]
2301 \& [% BLOCK half_wit %]
2302 \& This is just half...
2304 \& ...a complete block
2312 \& This is just half...
2316 .IX Subsection "STOP"
2317 The \f(CW\*(C`STOP\*(C'\fR directive can be used to indicate that the processor should stop
2318 gracefully without processing any more of the template document. This is a
2319 planned stop and the Template \fIprocess()\fR method will
2320 return a \fBtrue\fR value to the caller. This indicates that the template was
2321 processed successfully according to the directives within it.
2324 \& [% IF something.terrible.happened %]
2325 \& [% INCLUDE fatal/error.html %]
2332 \& [% USE DBI(mydsn) %]
2334 \& [% CATCH DBI.connect %]
2335 \& <h1>Cannot connect to the database: [% error.info %]</h1>
2337 \& We apologise for the inconvenience.
2339 \& [% INCLUDE footer %]
2344 .IX Subsection "CLEAR"
2345 The \f(CW\*(C`CLEAR\*(C'\fR directive can be used to clear the output buffer for the current
2346 enclosing block. It is most commonly used to clear the output generated
2347 from a \f(CW\*(C`TRY\*(C'\fR block up to the point where the error occurred.
2351 \& blah blah blah # this is normally left intact
2352 \& [% THROW some 'error' %] # up to the point of error
2355 \& [% CLEAR %] # clear the TRY output
2356 \& [% error %] # print error string
2360 .IX Header "Miscellaneous"
2362 .IX Subsection "META"
2363 The \f(CW\*(C`META\*(C'\fR directive allows simple metadata items to be defined within a
2364 template. These are evaluated when the template is parsed and as such may only
2365 contain simple values (e.g. it's not possible to interpolate other variables
2366 values into \f(CW\*(C`META\*(C'\fR variables).
2370 \& title = 'The Cat in the Hat'
2371 \& author = 'Dr. Seuss'
2376 The \f(CW\*(C`template\*(C'\fR variable contains a reference to the main template
2377 being processed. These metadata items may be retrieved as attributes
2381 \& <h1>[% template.title %]</h1>
2382 \& <h2>[% template.author %]</h2>
2385 The \f(CW\*(C`name\*(C'\fR and \f(CW\*(C`modtime\*(C'\fR metadata items are automatically defined for each
2386 template to contain its name and modification time in seconds since the epoch.
2389 \& [% USE date %] # use Date plugin to format time
2391 \& [% template.name %] last modified
2392 \& at [% date.format(template.modtime) %]
2395 The \f(CW\*(C`PRE_PROCESS\*(C'\fR and \f(CW\*(C`POST_PROCESS\*(C'\fR options allow common headers and
2396 footers to be added to all templates. The \f(CW\*(C`template\*(C'\fR reference is
2397 correctly defined when these templates are processed, allowing headers
2398 and footers to reference metadata items from the main template.
2401 \& $template = Template\->new({
2402 \& PRE_PROCESS => 'header',
2403 \& POST_PROCESS => 'footer',
2408 \& $template\->process('cat_in_hat');
2416 \& <title>[% template.title %]</title>
2425 \& title = 'The Cat in the Hat'
2426 \& author = 'Dr. Seuss'
2433 \& The cat in the hat sat on the mat.
2440 \& © [% template.year %] [% template.author %]
2445 The output generated from the above example is:
2450 \& <title>The Cat in the Hat</title>
2453 \& The cat in the hat sat on the mat.
2455 \& © 2000 Dr. Seuss
2460 .IX Subsection "TAGS"
2461 The \f(CW\*(C`TAGS\*(C'\fR directive can be used to set the \f(CW\*(C`START_TAG\*(C'\fR and \f(CW\*(C`END_TAG\*(C'\fR values
2462 on a per-template file basis.
2469 \& <+ INCLUDE header +>
2472 The \s-1TAGS\s0 directive may also be used to set a named \f(CW\*(C`TAG_STYLE\*(C'\fR
2476 \& <!\-\- INCLUDE header \-\->
2479 See the \s-1TAGS\s0 and \s-1TAG_STYLE\s0
2480 configuration options for further details.
2482 .IX Subsection "DEBUG"
2483 The \f(CW\*(C`DEBUG\*(C'\fR directive can be used to enable or disable directive debug
2484 messages within a template. The \f(CW\*(C`DEBUG\*(C'\fR configuration option must be
2485 set to include \f(CW\*(C`DEBUG_DIRS\*(C'\fR for the \f(CW\*(C`DEBUG\*(C'\fR directives to have any effect.
2486 If \f(CW\*(C`DEBUG_DIRS\*(C'\fR is not set then the parser will automatically ignore and
2487 remove any \f(CW\*(C`DEBUG\*(C'\fR directives.
2489 The \f(CW\*(C`DEBUG\*(C'\fR directive can be used with an \f(CW\*(C`on\*(C'\fR or \f(CW\*(C`off\*(C'\fR parameter to
2490 enable or disable directive debugging messages from that point
2491 forward. When enabled, the output of each directive in the generated
2492 output will be prefixed by a comment indicate the file, line and
2493 original directive text.
2497 \& directive debugging is on (assuming DEBUG option is set true)
2499 \& directive debugging is off
2502 The \f(CW\*(C`format\*(C'\fR parameter can be used to change the format of the debugging
2506 \& [% DEBUG format '<!\-\- $file line $line : [% $text %] \-\->' %]