1Template::Manual::DirecUtsievresC(o3n)tributed Perl DocuTmeemnptlaattieo:n:Manual::Directives(3)
2
3
4
6 Template::Manual::Directives - Template directives
7
9 GET
10 The "GET" directive retrieves and outputs the value of the named
11 variable.
12
13 [% GET foo %]
14
15 The "GET" keyword is optional. A variable can be specified in a
16 directive tag by itself.
17
18 [% foo %]
19
20 The variable can have an unlimited number of elements, each separated
21 by a dot. Each element can have arguments specified within parentheses.
22
23 [% foo %]
24 [% bar.baz %]
25 [% biz.baz(10) %]
26 ...etc...
27
28 See Template::Manual::Variables for a full discussion on template
29 variables.
30
31 You can also specify expressions using the logical ("and", "or", "not",
32 "?", ":") and mathematic operators ("+", "-", "*", "/", "%", "mod",
33 "div").
34
35 [% template.title or default.title %]
36
37 [% score * 100 %]
38
39 [% order.nitems ? checkout(order.total) : 'no items' %]
40
41 The "div" operator returns the integer result of division. Both "%"
42 and "mod" return the modulus (i.e. remainder) of division.
43
44 [% 15 / 6 %] # 2.5
45 [% 15 div 6 %] # 2
46 [% 15 mod 6 %] # 3
47
48 CALL
49 The "CALL" directive is similar to "GET" in evaluating the variable
50 named, but doesn't print the result returned. This can be useful when
51 a variable is bound to a sub-routine or object method which you want to
52 call but aren't interested in the value returned.
53
54 [% CALL dbi.disconnect %]
55
56 [% CALL inc_page_counter(page_count) %]
57
58 SET
59 The "SET" directive allows you to assign new values to existing
60 variables or create new temporary variables.
61
62 [% SET title = 'Hello World' %]
63
64 The "SET" keyword is also optional.
65
66 [% title = 'Hello World' %]
67
68 Variables may be assigned the values of other variables, unquoted
69 numbers (2.718), literal text ('single quotes') or quoted text ("double
70 quotes"). In the latter case, any variable references within the text
71 will be interpolated when the string is evaluated. Variables should be
72 prefixed by "$", using curly braces to explicitly scope the variable
73 name where necessary.
74
75 [% foo = 'Foo' %] # literal value 'Foo'
76 [% bar = foo %] # value of variable 'foo'
77 [% cost = '$100' %] # literal value '$100'
78 [% item = "$bar: ${cost}.00" %] # value "Foo: $100.00"
79
80 Multiple variables may be assigned in the same directive and are
81 evaluated in the order specified. Thus, the above could have been
82 written:
83
84 [% foo = 'Foo'
85 bar = foo
86 cost = '$100'
87 item = "$bar: ${cost}.00"
88 %]
89
90 Simple expressions can also be used, as per "GET".
91
92 [% ten = 10
93 twenty = 20
94 thirty = twenty + ten
95 forty = 2 * twenty
96 fifty = 100 div 2
97 six = twenty mod 7
98 %]
99
100 You can concatenate strings together using the ' _ ' operator. In Perl
101 5, the "." is used for string concatenation, but in Perl 6, as in the
102 Template Toolkit, the "." will be used as the method calling operator
103 and ' _ ' will be used for string concatenation. Note that the
104 operator must be specified with surrounding whitespace which, as Larry
105 says, is construed as a feature:
106
107 [% copyright = '(C) Copyright' _ year _ ' ' _ author %]
108
109 You can, of course, achieve a similar effect with double quoted string
110 interpolation.
111
112 [% copyright = "(C) Copyright $year $author" %]
113
114 DEFAULT
115 The "DEFAULT" directive is similar to "SET" but only updates variables
116 that are currently undefined or have no "true" value (in the Perl
117 sense).
118
119 [% DEFAULT
120 name = 'John Doe'
121 id = 'jdoe'
122 %]
123
124 This can be particularly useful in common template components to ensure
125 that some sensible default are provided for otherwise undefined
126 variables.
127
128 [% DEFAULT
129 title = 'Hello World'
130 bgcol = '#ffffff'
131 %]
132 <html>
133 <head>
134 <title>[% title %]</title>
135 </head>
136 <body bgcolor="[% bgcol %]">
137 ...etc...
138
140 INSERT
141 The "INSERT" directive is used to insert the contents of an external
142 file at the current position.
143
144 [% INSERT myfile %]
145
146 No attempt to parse or process the file is made. The contents,
147 possibly including any embedded template directives, are inserted
148 intact.
149
150 The filename specified should be relative to one of the "INCLUDE_PATH"
151 directories. Absolute (i.e. starting with "/") and relative (i.e.
152 starting with ".") filenames may be used if the "ABSOLUTE" and
153 "RELATIVE" options are set, respectively. Both these options are
154 disabled by default.
155
156 my $template = Template->new({
157 INCLUDE_PATH => '/here:/there',
158 });
159
160 $template->process('myfile');
161
162 myfile:
163
164 [% INSERT foo %] # looks for /here/foo then /there/foo
165 [% INSERT /etc/passwd %] # file error: ABSOLUTE not set
166 [% INSERT ../secret %] # file error: RELATIVE not set
167
168 For convenience, the filename does not need to be quoted as long as it
169 contains only alphanumeric characters, underscores, dots or forward
170 slashes. Names containing any other characters should be quoted.
171
172 [% INSERT misc/legalese.txt %]
173 [% INSERT 'dos98/Program Files/stupid' %]
174
175 To evaluate a variable to specify a filename, you should explicitly
176 prefix it with a "$" or use double-quoted string interpolation.
177
178 [% language = 'en'
179 legalese = 'misc/legalese.txt'
180 %]
181
182 [% INSERT $legalese %] # misc/legalese.txt
183 [% INSERT "$language/$legalese" %] # en/misc/legalese.txt
184
185 Multiple files can be specified using "+" as a delimiter. All files
186 should be unquoted names or quoted strings. Any variables should be
187 interpolated into double-quoted strings.
188
189 [% INSERT legalese.txt + warning.txt %]
190 [% INSERT "$legalese" + warning.txt %] # requires quoting
191
192 INCLUDE
193 The "INCLUDE" directive is used to process and include the output of
194 another template file or block.
195
196 [% INCLUDE header %]
197
198 If a "BLOCK" of the specified name is defined in the same file, or in a
199 file from which the current template has been called (i.e. a parent
200 template) then it will be used in preference to any file of the same
201 name.
202
203 [% INCLUDE table %] # uses BLOCK defined below
204
205 [% BLOCK table %]
206 <table>
207 ...
208 </table>
209 [% END %]
210
211 If a "BLOCK" definition is not currently visible then the template name
212 should be a file relative to one of the "INCLUDE_PATH" directories, or
213 an absolute or relative file name if the "ABSOLUTE"/"RELATIVE" options
214 are appropriately enabled. The "INCLUDE" directive automatically
215 quotes the filename specified, as per "INSERT" described above. When a
216 variable contains the name of the template for the "INCLUDE" directive,
217 it should be explicitly prefixed by "$" or double-quoted
218
219 [% myheader = 'my/misc/header' %]
220 [% INCLUDE myheader %] # 'myheader'
221 [% INCLUDE $myheader %] # 'my/misc/header'
222 [% INCLUDE "$myheader" %] # 'my/misc/header'
223
224 Any template directives embedded within the file will be processed
225 accordingly. All variables currently defined will be visible and
226 accessible from within the included template.
227
228 [% title = 'Hello World' %]
229 [% INCLUDE header %]
230 <body>
231 ...
232
233 header:
234
235 <html>
236 <title>[% title %]</title>
237
238 output:
239
240 <html>
241 <title>Hello World</title>
242 <body>
243 ...
244
245 Local variable definitions may be specified after the template name,
246 temporarily masking any existing variables. Insignificant whitespace
247 is ignored within directives so you can add variable definitions on the
248 same line, the next line or split across several line with comments
249 interspersed, if you prefer.
250
251 [% INCLUDE table %]
252
253 [% INCLUDE table title="Active Projects" %]
254
255 [% INCLUDE table
256 title = "Active Projects"
257 bgcolor = "#80ff00" # chartreuse
258 border = 2
259 %]
260
261 The "INCLUDE" directive localises (i.e. copies) all variables before
262 processing the template. Any changes made within the included template
263 will not affect variables in the including template.
264
265 [% foo = 10 %]
266
267 foo is originally [% foo %]
268 [% INCLUDE bar %]
269 foo is still [% foo %]
270
271 [% BLOCK bar %]
272 foo was [% foo %]
273 [% foo = 20 %]
274 foo is now [% foo %]
275 [% END %]
276
277 output:
278
279 foo is originally 10
280 foo was 10
281 foo is now 20
282 foo is still 10
283
284 Technical Note: the localisation of the stash (that is, the process by
285 which variables are copied before an "INCLUDE" to prevent being
286 overwritten) is only skin deep. The top-level variable namespace
287 (hash) is copied, but no attempt is made to perform a deep-copy of
288 other structures (hashes, arrays, objects, etc.) Therefore, a "foo"
289 variable referencing a hash will be copied to create a new "foo"
290 variable but which points to the same hash array. Thus, if you update
291 compound variables (e.g. "foo.bar") then you will change the original
292 copy, regardless of any stash localisation. If you're not worried
293 about preserving variable values, or you trust the templates you're
294 including then you might prefer to use the "PROCESS" directive which is
295 faster by virtue of not performing any localisation.
296
297 You can specify dotted variables as "local" variables to an "INCLUDE"
298 directive. However, be aware that because of the localisation issues
299 explained above (if you skipped the previous Technical Note above then
300 you might want to go back and read it or skip this section too), the
301 variables might not actually be "local". If the first element of the
302 variable name already references a hash array then the variable update
303 will affect the original variable.
304
305 [% foo = {
306 bar = 'Baz'
307 }
308 %]
309
310 [% INCLUDE somefile foo.bar='Boz' %]
311
312 [% foo.bar %] # Boz
313
314 This behaviour can be a little unpredictable (and may well be improved
315 upon in a future version). If you know what you're doing with it and
316 you're sure that the variables in question are defined (nor not) as you
317 expect them to be, then you can rely on this feature to implement some
318 powerful "global" data sharing techniques. Otherwise, you might prefer
319 to steer well clear and always pass simple (undotted) variables as
320 parameters to "INCLUDE" and other similar directives.
321
322 If you want to process several templates in one go then you can specify
323 each of their names (quoted or unquoted names only, no unquoted
324 $variables) joined together by "+". The "INCLUDE" directive will then
325 process them in order.
326
327 [% INCLUDE html/header + "site/$header" + site/menu
328 title = "My Groovy Web Site"
329 %]
330
331 The variable stash is localised once and then the templates specified
332 are processed in order, all within that same variable context. This
333 makes it slightly faster than specifying several separate "INCLUDE"
334 directives (because you only clone the variable stash once instead of n
335 times), but not quite as "safe" because any variable changes in the
336 first file will be visible in the second, third and so on. This might
337 be what you want, of course, but then again, it might not.
338
339 PROCESS
340 The PROCESS directive is similar to "INCLUDE" but does not perform any
341 localisation of variables before processing the template. Any changes
342 made to variables within the included template will be visible in the
343 including template.
344
345 [% foo = 10 %]
346
347 foo is [% foo %]
348 [% PROCESS bar %]
349 foo is [% foo %]
350
351 [% BLOCK bar %]
352 [% foo = 20 %]
353 changed foo to [% foo %]
354 [% END %]
355
356 output:
357
358 foo is 10
359 changed foo to 20
360 foo is 20
361
362 Parameters may be specified in the "PROCESS" directive, but these too
363 will become visible changes to current variable values.
364
365 [% foo = 10 %]
366 foo is [% foo %]
367 [% PROCESS bar
368 foo = 20
369 %]
370 foo is [% foo %]
371
372 [% BLOCK bar %]
373 this is bar, foo is [% foo %]
374 [% END %]
375
376 output:
377
378 foo is 10
379 this is bar, foo is 20
380 foo is 20
381
382 The "PROCESS" directive is slightly faster than "INCLUDE" because it
383 avoids the need to localise (i.e. copy) the variable stash before
384 processing the template. As with "INSERT" and "INCLUDE", the first
385 parameter does not need to be quoted as long as it contains only
386 alphanumeric characters, underscores, periods or forward slashes. A
387 "$" prefix can be used to explicitly indicate a variable which should
388 be interpolated to provide the template name:
389
390 [% myheader = 'my/misc/header' %]
391 [% PROCESS myheader %] # 'myheader'
392 [% PROCESS $myheader %] # 'my/misc/header'
393
394 As with "INCLUDE", multiple templates can be specified, delimited by
395 "+", and are processed in order.
396
397 [% PROCESS html/header + my/header %]
398
399 WRAPPER
400 It's not unusual to find yourself adding common headers and footers to
401 pages or sub-sections within a page. Something like this:
402
403 [% INCLUDE section/header
404 title = 'Quantum Mechanics'
405 %]
406 Quantum mechanics is a very interesting subject wish
407 should prove easy for the layman to fully comprehend.
408 [% INCLUDE section/footer %]
409
410 [% INCLUDE section/header
411 title = 'Desktop Nuclear Fusion for under $50'
412 %]
413 This describes a simple device which generates significant
414 sustainable electrical power from common tap water by process
415 of nuclear fusion.
416 [% INCLUDE section/footer %]
417
418 The individual template components being included might look like
419 these:
420
421 section/header:
422
423 <p>
424 <h2>[% title %]</h2>
425
426 section/footer:
427
428 </p>
429
430 The "WRAPPER" directive provides a way of simplifying this a little. It
431 encloses a block up to a matching "END" directive, which is first
432 processed to generate some output. This is then passed to the named
433 template file or "BLOCK" as the "content" variable.
434
435 [% WRAPPER section
436 title = 'Quantum Mechanics'
437 %]
438 Quantum mechanics is a very interesting subject wish
439 should prove easy for the layman to fully comprehend.
440 [% END %]
441
442 [% WRAPPER section
443 title = 'Desktop Nuclear Fusion for under $50'
444 %]
445 This describes a simple device which generates significant
446 sustainable electrical power from common tap water by process
447 of nuclear fusion.
448 [% END %]
449
450 The single 'section' template can then be defined as:
451
452 <h2>[% title %]</h2>
453 <p>
454 [% content %]
455 </p>
456
457 Like other block directives, it can be used in side-effect notation:
458
459 [% INSERT legalese.txt WRAPPER big_bold_table %]
460
461 It's also possible to specify multiple templates to a "WRAPPER"
462 directive. The specification order indicates outermost to innermost
463 wrapper templates. For example, given the following template block
464 definitions:
465
466 [% BLOCK bold %]<b>[% content %]</b>[% END %]
467 [% BLOCK italic %]<i>[% content %]</i>[% END %]
468
469 the directive
470
471 [% WRAPPER bold+italic %]Hello World[% END %]
472
473 would generate the following output:
474
475 <b><i>Hello World</i></b>
476
477 BLOCK
478 The "BLOCK"..."END" construct can be used to define template component
479 blocks which can be processed with the "INCLUDE", "PROCESS" and
480 "WRAPPER" directives.
481
482 [% BLOCK tabrow %]
483 <tr>
484 <td>[% name %]<td>
485 <td>[% email %]</td>
486 </tr>
487 [% END %]
488
489 <table>
490 [% PROCESS tabrow name='Fred' email='fred@nowhere.com' %]
491 [% PROCESS tabrow name='Alan' email='alan@nowhere.com' %]
492 </table>
493
494 A "BLOCK" definition can be used before it is defined, as long as the
495 definition resides in the same file. The block definition itself does
496 not generate any output.
497
498 [% PROCESS tmpblk %]
499
500 [% BLOCK tmpblk %] This is OK [% END %]
501
502 You can use an anonymous "BLOCK" to capture the output of a template
503 fragment.
504
505 [% julius = BLOCK %]
506 And Caesar's spirit, ranging for revenge,
507 With Ate by his side come hot from hell,
508 Shall in these confines with a monarch's voice
509 Cry 'Havoc', and let slip the dogs of war;
510 That this foul deed shall smell above the earth
511 With carrion men, groaning for burial.
512 [% END %]
513
514 Like a named block, it can contain any other template directives which
515 are processed when the block is defined. The output generated by the
516 block is then assigned to the variable "julius".
517
518 Anonymous "BLOCK"s can also be used to define block macros. The
519 enclosing block is processed each time the macro is called.
520
521 [% MACRO locate BLOCK %]
522 The [% animal %] sat on the [% place %].
523 [% END %]
524
525 [% locate(animal='cat', place='mat') %] # The cat sat on the mat
526 [% locate(animal='dog', place='log') %] # The dog sat on the log
527
529 IF / UNLESS / ELSIF / ELSE
530 The "IF" and "UNLESS" directives can be used to process or ignore a
531 block based on some run-time condition.
532
533 [% IF frames %]
534 [% INCLUDE frameset %]
535 [% END %]
536
537 [% UNLESS text_mode %]
538 [% INCLUDE biglogo %]
539 [% END %]
540
541 Multiple conditions may be joined with "ELSIF" and/or "ELSE" blocks.
542
543 [% IF age < 10 %]
544 Hello [% name %], does your mother know you're
545 using her AOL account?
546 [% ELSIF age < 18 %]
547 Sorry, you're not old enough to enter
548 (and too dumb to lie about your age)
549 [% ELSE %]
550 Welcome [% name %].
551 [% END %]
552
553 The following conditional and boolean operators may be used:
554
555 == != < <= > >= && || ! and or not
556
557 Conditions may be arbitrarily complex and are evaluated with the same
558 precedence as in Perl. Parenthesis may be used to explicitly determine
559 evaluation order.
560
561 # ridiculously contrived complex example
562 [% IF (name == 'admin' || uid <= 0) && mode == 'debug' %]
563 I'm confused.
564 [% ELSIF more > less %]
565 That's more or less correct.
566 [% END %]
567
568 The "and", "or" and "not" operator are provided as aliases for "&&",
569 "||" and "!", respectively. Unlike Perl, which treats "and", "or" and
570 "not" as separate, lower-precedence versions of the other operators,
571 the Template Toolkit performs a straightforward substitution of "and"
572 for "&&", and so on. That means that "and", "or" and "not" have the
573 same operator precedence as "&&", "||" and "!".
574
575 SWITCH / CASE
576 The "SWITCH" / "CASE" construct can be used to perform a multi-way
577 conditional test. The "SWITCH" directive expects an expression which
578 is first evaluated and then compared against each CASE statement in
579 turn. Each "CASE" directive should contain a single value or a list of
580 values which should match. "CASE" may also be left blank or written as
581 "[% CASE DEFAULT %]" to specify a default match. Only one "CASE"
582 matches, there is no drop-through between "CASE" statements.
583
584 [% SWITCH myvar %]
585 [% CASE 'value1' %]
586 ...
587 [% CASE ['value2', 'value3'] %] # multiple values
588 ...
589 [% CASE myhash.keys %] # ditto
590 ...
591 [% CASE %] # default
592 ...
593 [% END %]
594
596 FOREACH
597 The "FOREACH" directive will iterate through the items in a list,
598 processing the enclosed block for each one.
599
600 [% foo = 'Foo'
601 items = [ 'one', 'two', 'three' ]
602 %]
603
604 Things:
605 [% FOREACH thing IN [ foo 'Bar' "$foo Baz" ] %]
606 * [% thing %]
607 [% END %]
608
609 Items:
610 [% FOREACH i IN items %]
611 * [% i %]
612 [% END %]
613
614 Stuff:
615 [% stuff = [ foo "$foo Bar" ] %]
616 [% FOREACH s IN stuff %]
617 * [% s %]
618 [% END %]
619
620 output:
621
622 Things:
623 * Foo
624 * Bar
625 * Foo Baz
626
627 Items:
628 * one
629 * two
630 * three
631
632 Stuff:
633 * Foo
634 * Foo Bar
635
636 You can use also use "=" instead of "IN" if you prefer.
637
638 [% FOREACH i = items %]
639
640 When the "FOREACH" directive is used without specifying a target
641 variable, any iterated values which are hash references will be
642 automatically imported.
643
644 [% userlist = [
645 { id => 'tom', name => 'Thomas' },
646 { id => 'dick', name => 'Richard' },
647 { id => 'larry', name => 'Lawrence' },
648 ]
649 %]
650
651 [% FOREACH user IN userlist %]
652 [% user.id %] [% user.name %]
653 [% END %]
654
655 short form:
656
657 [% FOREACH userlist %]
658 [% id %] [% name %]
659 [% END %]
660
661 Note that this particular usage creates a localised variable context to
662 prevent the imported hash keys from overwriting any existing variables.
663 The imported definitions and any other variables defined in such a
664 "FOREACH" loop will be lost at the end of the loop, when the previous
665 context and variable values are restored.
666
667 However, under normal operation, the loop variable remains in scope
668 after the "FOREACH" loop has ended (caveat: overwriting any variable
669 previously in scope). This is useful as the loop variable is secretly
670 an iterator object (see below) and can be used to analyse the last
671 entry processed by the loop.
672
673 The "FOREACH" directive can also be used to iterate through the entries
674 in a hash array. Each entry in the hash is returned in sorted order
675 (based on the key) as a hash array containing 'key' and 'value' items.
676
677 [% users = {
678 tom => 'Thomas',
679 dick => 'Richard',
680 larry => 'Lawrence',
681 }
682 %]
683
684 [% FOREACH u IN users %]
685 * [% u.key %] : [% u.value %]
686 [% END %]
687
688 Output:
689
690 * dick : Richard
691 * larry : Lawrence
692 * tom : Thomas
693
694 The "NEXT" directive starts the next iteration in the "FOREACH" loop.
695
696 [% FOREACH user IN userlist %]
697 [% NEXT IF user.isguest %]
698 Name: [% user.name %] Email: [% user.email %]
699 [% END %]
700
701 The "LAST" directive can be used to prematurely exit the loop. "BREAK"
702 is also provided as an alias for "LAST".
703
704 [% FOREACH match IN results.nsort('score').reverse %]
705 [% LAST IF match.score < 50 %]
706 [% match.score %] : [% match.url %]
707 [% END %]
708
709 The "FOREACH" directive is implemented using the Template::Iterator
710 module. A reference to the iterator object for a "FOREACH" directive
711 is implicitly available in the "loop" variable. The following methods
712 can be called on the "loop" iterator.
713
714 size() number of elements in the list
715 max() index number of last element (size - 1)
716 index() index of current iteration from 0 to max()
717 count() iteration counter from 1 to size() (i.e. index() + 1)
718 first() true if the current iteration is the first
719 last() true if the current iteration is the last
720 prev() return the previous item in the list
721 next() return the next item in the list
722
723 See Template::Iterator for further details.
724
725 Example:
726
727 [% FOREACH item IN [ 'foo', 'bar', 'baz' ] -%]
728 [%- "<ul>\n" IF loop.first %]
729 <li>[% loop.count %]/[% loop.size %]: [% item %]
730 [%- "</ul>\n" IF loop.last %]
731 [% END %]
732
733 Output:
734
735 <ul>
736 <li>1/3: foo
737 <li>2/3: bar
738 <li>3/3: baz
739 </ul>
740
741 Nested loops will work as expected, with the "loop" variable correctly
742 referencing the innermost loop and being restored to any previous value
743 (i.e. an outer loop) at the end of the loop.
744
745 [% FOREACH group IN grouplist;
746 # loop => group iterator
747 "Groups:\n" IF loop.first;
748
749 FOREACH user IN group.userlist;
750 # loop => user iterator
751 "$loop.count: $user.name\n";
752 END;
753
754 # loop => group iterator
755 "End of Groups\n" IF loop.last;
756 END
757 %]
758
759 The "iterator" plugin can also be used to explicitly create an iterator
760 object. This can be useful within nested loops where you need to keep
761 a reference to the outer iterator within the inner loop. The iterator
762 plugin effectively allows you to create an iterator by a name other
763 than "loop". See Template::Plugin::Iterator for further details.
764
765 [% USE giter = iterator(grouplist) %]
766
767 [% FOREACH group IN giter %]
768 [% FOREACH user IN group.userlist %]
769 user #[% loop.count %] in
770 group [% giter.count %] is
771 named [% user.name %]
772 [% END %]
773 [% END %]
774
775 WHILE
776 The "WHILE" directive can be used to repeatedly process a template
777 block while a conditional expression evaluates true. The expression
778 may be arbitrarily complex as per "IF" / "UNLESS".
779
780 [% WHILE total < 100 %]
781 ...
782 [% total = calculate_new_total %]
783 [% END %]
784
785 An assignment can be enclosed in parenthesis to evaluate the assigned
786 value.
787
788 [% WHILE (user = get_next_user_record) %]
789 [% user.name %]
790 [% END %]
791
792 The "NEXT" directive can be used to start the next iteration of a
793 "WHILE" loop and "BREAK" can be used to exit the loop, both as per
794 "FOREACH".
795
796 The Template Toolkit uses a failsafe counter to prevent runaway "WHILE"
797 loops which would otherwise never terminate. If the loop exceeds 1000
798 iterations then an "undef" exception will be thrown, reporting the
799 error:
800
801 WHILE loop terminated (> 1000 iterations)
802
803 The $Template::Directive::WHILE_MAX variable controls this behaviour
804 and can be set to a higher value if necessary.
805
807 FILTER
808 The "FILTER" directive can be used to post-process the output of a
809 block. A number of standard filters are provided with the Template
810 Toolkit. The "html" filter, for example, escapes the '<', '>' and '&'
811 characters to prevent them from being interpreted as HTML tags or
812 entity reference markers.
813
814 [% FILTER html %]
815 HTML text may have < and > characters embedded
816 which you want converted to the correct HTML entities.
817 [% END %]
818
819 output:
820
821 HTML text may have < and > characters embedded
822 which you want converted to the correct HTML entities.
823
824 The "FILTER" directive can also follow various other non-block
825 directives. For example:
826
827 [% INCLUDE mytext FILTER html %]
828
829 The "|" character can also be used as an alias for "FILTER".
830
831 [% INCLUDE mytext | html %]
832
833 Multiple filters can be chained together and will be called in
834 sequence.
835
836 [% INCLUDE mytext FILTER html FILTER html_para %]
837
838 or
839
840 [% INCLUDE mytext | html | html_para %]
841
842 Filters come in two flavours, known as 'static' or 'dynamic'. A static
843 filter is a simple subroutine which accepts a text string as the only
844 argument and returns the modified text. The "html" filter is an
845 example of a static filter, implemented as:
846
847 sub html_filter {
848 my $text = shift;
849 for ($text) {
850 s/&/&/g;
851 s/</</g;
852 s/>/>/g;
853 }
854 return $text;
855 }
856
857 Dynamic filters can accept arguments which are specified when the
858 filter is called from a template. The "repeat" filter is such an
859 example, accepting a numerical argument which specifies the number of
860 times that the input text should be repeated.
861
862 [% FILTER repeat(3) %]blah [% END %]
863
864 output:
865
866 blah blah blah
867
868 These are implemented as filter 'factories'. The factory subroutine is
869 passed a reference to the current Template::Context object along with
870 any additional arguments specified. It should then return a subroutine
871 reference (e.g. a closure) which implements the filter. The "repeat"
872 filter factory is implemented like this:
873
874 sub repeat_filter_factory {
875 my ($context, $iter) = @_;
876 $iter = 1 unless defined $iter;
877
878 return sub {
879 my $text = shift;
880 $text = '' unless defined $text;
881 return join('\n', $text) x $iter;
882 }
883 }
884
885 The "FILTERS" option, described in Template::Manual::Config, allows
886 custom filters to be defined when a Template object is instantiated.
887 The define_filter() method allows further filters to be defined at any
888 time.
889
890 When using a filter, it is possible to assign an alias to it for
891 further use. This is most useful for dynamic filters that you want to
892 re-use with the same configuration.
893
894 [% FILTER echo = repeat(2) %]
895 Is there anybody out there?
896 [% END %]
897
898 [% FILTER echo %]
899 Mother, should I build a wall?
900 [% END %]
901
902 Output:
903
904 Is there anybody out there?
905 Is there anybody out there?
906
907 Mother, should I build a wall?
908 Mother, should I build a wall?
909
910 The "FILTER" directive automatically quotes the name of the filter. As
911 with "INCLUDE" et al, you can use a variable to provide the name of the
912 filter, prefixed by "$".
913
914 [% myfilter = 'html' %]
915 [% FILTER $myfilter %] # same as [% FILTER html %]
916 ...
917 [% END %]
918
919 A template variable can also be used to define a static filter
920 subroutine. However, the Template Toolkit will automatically call any
921 subroutine bound to a variable and use the value returned. Thus, the
922 above example could be implemented as:
923
924 my $vars = {
925 myfilter => sub { return 'html' },
926 };
927
928 template:
929
930 [% FILTER $myfilter %] # same as [% FILTER html %]
931 ...
932 [% END %]
933
934 To define a template variable that evaluates to a subroutine reference
935 that can be used by the "FILTER" directive, you should create a
936 subroutine that, when called automatically by the Template Toolkit,
937 returns another subroutine reference which can then be used to perform
938 the filter operation. Note that only static filters can be implemented
939 in this way.
940
941 my $vars = {
942 myfilter => sub { \&my_filter_sub },
943 };
944
945 sub my_filter_sub {
946 my $text = shift;
947 # do something
948 return $text;
949 }
950
951 template:
952
953 [% FILTER $myfilter %]
954 ...
955 [% END %]
956
957 Alternately, you can bless a subroutine reference into a class (any
958 class will do) to fool the Template Toolkit into thinking it's an
959 object rather than a subroutine. This will then bypass the automatic
960 "call-a-subroutine-to-return-a-value" magic.
961
962 my $vars = {
963 myfilter => bless(\&my_filter_sub, 'anything_you_like'),
964 };
965
966 template:
967
968 [% FILTER $myfilter %]
969 ...
970 [% END %]
971
972 Filters bound to template variables remain local to the variable
973 context in which they are defined. That is, if you define a filter in a
974 "PERL" block within a template that is loaded via "INCLUDE", then the
975 filter definition will only exist until the end of that template when
976 the stash is delocalised, restoring the previous variable state. If you
977 want to define a filter which persists for the lifetime of the
978 processor, or define additional dynamic filter factories, then you can
979 call the define_filter() method on the current Template::Context
980 object.
981
982 See Template::Manual::Filters for a complete list of available filters,
983 their descriptions and examples of use.
984
985 USE
986 The "USE" directive can be used to load and initialise "plugin"
987 extension modules.
988
989 [% USE myplugin %]
990
991 A plugin is a regular Perl module that conforms to a particular object-
992 oriented interface, allowing it to be loaded into and used
993 automatically by the Template Toolkit. For details of this interface
994 and information on writing plugins, consult Template::Plugin.
995
996 A number of standard plugins are included with the Template Toolkit
997 (see below and Template::Manual::Plugins). The names of these standard
998 plugins are case insensitive.
999
1000 [% USE CGI %] # => Template::Plugin::CGI
1001 [% USE Cgi %] # => Template::Plugin::CGI
1002 [% USE cgi %] # => Template::Plugin::CGI
1003
1004 You can also define further plugins using the "PLUGINS" option.
1005
1006 my $tt = Template->new({
1007 PLUGINS => {
1008 foo => 'My::Plugin::Foo',
1009 bar => 'My::Plugin::Bar',
1010 },
1011 });
1012
1013 The recommended convention is to specify these plugin names in lower
1014 case. The Template Toolkit first looks for an exact case-sensitive
1015 match and then tries the lower case conversion of the name specified.
1016
1017 [% USE Foo %] # look for 'Foo' then 'foo'
1018
1019 If you define all your "PLUGINS" with lower case names then they will
1020 be located regardless of how the user specifies the name in the "USE"
1021 directive. If, on the other hand, you define your "PLUGINS" with upper
1022 or mixed case names then the name specified in the "USE" directive must
1023 match the case exactly.
1024
1025 If the plugin isn't defined in either the standard plugins
1026 ($Template::Plugins::STD_PLUGINS) or via the "PLUGINS" option, then the
1027 "PLUGIN_BASE" is searched.
1028
1029 In this case the plugin name is case-sensitive. It is appended to each
1030 of the "PLUGIN_BASE" module namespaces in turn (default:
1031 "Template::Plugin") to construct a full module name which it attempts
1032 to locate and load. Any periods, '"."', in the name will be converted
1033 to '"::"'.
1034
1035 [% USE MyPlugin %] # => Template::Plugin::MyPlugin
1036 [% USE Foo.Bar %] # => Template::Plugin::Foo::Bar
1037
1038 The "LOAD_PERL" option (disabled by default) provides a further way by
1039 which external Perl modules may be loaded. If a regular Perl module
1040 (i.e. not a "Template::Plugin::*" or other module relative to some
1041 "PLUGIN_BASE") supports an object-oriented interface and a "new()"
1042 constructor then it can be loaded and instantiated automatically. The
1043 following trivial example shows how the IO::File module might be used.
1044
1045 [% USE file = IO.File('/tmp/mydata') %]
1046
1047 [% WHILE (line = file.getline) %]
1048 <!-- [% line %] -->
1049 [% END %]
1050
1051 Any additional parameters supplied in parenthesis after the plugin name
1052 will be also be passed to the "new()" constructor. A reference to the
1053 current Template::Context object is passed as the first parameter.
1054
1055 [% USE MyPlugin('foo', 123) %]
1056
1057 equivalent to:
1058
1059 Template::Plugin::MyPlugin->new($context, 'foo', 123);
1060
1061 The only exception to this is when a module is loaded via the
1062 "LOAD_PERL" option. In this case the $context reference is not passed
1063 to the "new()" constructor. This is based on the assumption that the
1064 module is a regular Perl module rather than a Template Toolkit plugin
1065 so isn't expecting a context reference and wouldn't know what to do
1066 with it anyway.
1067
1068 Named parameters may also be specified. These are collated into a hash
1069 which is passed by reference as the last parameter to the constructor,
1070 as per the general code calling interface.
1071
1072 [% USE url('/cgi-bin/foo', mode='submit', debug=1) %]
1073
1074 equivalent to:
1075
1076 Template::Plugin::URL->new(
1077 $context,
1078 '/cgi-bin/foo'
1079 { mode => 'submit', debug => 1 }
1080 );
1081
1082 The plugin may represent any data type; a simple variable, hash, list
1083 or code reference, but in the general case it will be an object
1084 reference. Methods can be called on the object (or the relevant
1085 members of the specific data type) in the usual way:
1086
1087 [% USE table(mydata, rows=3) %]
1088
1089 [% FOREACH row IN table.rows %]
1090 <tr>
1091 [% FOREACH item IN row %]
1092 <td>[% item %]</td>
1093 [% END %]
1094 </tr>
1095 [% END %]
1096
1097 An alternative name may be provided for the plugin by which it can be
1098 referenced:
1099
1100 [% USE scores = table(myscores, cols=5) %]
1101
1102 [% FOREACH row IN scores.rows %]
1103 ...
1104 [% END %]
1105
1106 You can use this approach to create multiple plugin objects with
1107 different configurations. This example shows how the format plugin is
1108 used to create sub-routines bound to variables for formatting text as
1109 per "printf()".
1110
1111 [% USE bold = format('<b>%s</b>') %]
1112 [% USE ital = format('<i>%s</i>') %]
1113 [% bold('This is bold') %]
1114 [% ital('This is italic') %]
1115
1116 Output:
1117
1118 <b>This is bold</b>
1119 <i>This is italic</i>
1120
1121 This next example shows how the URL plugin can be used to build dynamic
1122 URLs from a base part and optional query parameters.
1123
1124 [% USE mycgi = URL('/cgi-bin/foo.pl', debug=1) %]
1125 <a href="[% mycgi %]">...
1126 <a href="[% mycgi(mode='submit') %]"...
1127
1128 Output:
1129
1130 <a href="/cgi-bin/foo.pl?debug=1">...
1131 <a href="/cgi-bin/foo.pl?mode=submit&debug=1">...
1132
1133 The CGI plugin is an example of one which delegates to another Perl
1134 module. In this case, to Lincoln Stein's "CGI" module. All of the
1135 methods provided by the "CGI" module are available via the plugin.
1136
1137 [% USE CGI;
1138 CGI.start_form;
1139 CGI.checkbox_group( name = 'colours',
1140 values = [ 'red' 'green' 'blue' ] );
1141 CGI.popup_menu( name = 'items',
1142 values = [ 'foo' 'bar' 'baz' ] );
1143 CGI.end_form
1144 %]
1145
1146 See Template::Manual::Plugins for more information on the plugins
1147 distributed with the toolkit or available from CPAN.
1148
1149 MACRO
1150 The "MACRO" directive allows you to define a directive or directive
1151 block which is then evaluated each time the macro is called.
1152
1153 [% MACRO header INCLUDE header %]
1154
1155 Calling the macro as:
1156
1157 [% header %]
1158
1159 is then equivalent to:
1160
1161 [% INCLUDE header %]
1162
1163 Macros can be passed named parameters when called. These values remain
1164 local to the macro.
1165
1166 [% header(title='Hello World') %]
1167
1168 equivalent to:
1169
1170 [% INCLUDE header title='Hello World' %]
1171
1172 A "MACRO" definition may include parameter names. Values passed to the
1173 macros are then mapped to these local variables. Other named
1174 parameters may follow these.
1175
1176 [% MACRO header(title) INCLUDE header %]
1177 [% header('Hello World') %]
1178 [% header('Hello World', bgcol='#123456') %]
1179
1180 equivalent to:
1181
1182 [% INCLUDE header title='Hello World' %]
1183 [% INCLUDE header title='Hello World' bgcol='#123456' %]
1184
1185 Here's another example, defining a macro for display numbers in comma-
1186 delimited groups of 3, using the chunk and join virtual method.
1187
1188 [% MACRO number(n) GET n.chunk(-3).join(',') %]
1189 [% number(1234567) %] # 1,234,567
1190
1191 A "MACRO" may precede any directive and must conform to the structure
1192 of the directive.
1193
1194 [% MACRO header IF frames %]
1195 [% INCLUDE frames/header %]
1196 [% ELSE %]
1197 [% INCLUDE header %]
1198 [% END %]
1199
1200 [% header %]
1201
1202 A "MACRO" may also be defined as an anonymous "BLOCK". The block will
1203 be evaluated each time the macro is called.
1204
1205 [% MACRO header BLOCK %]
1206 ...content...
1207 [% END %]
1208
1209 [% header %]
1210
1211 If you've got the "EVAL_PERL" option set, then you can even define a
1212 "MACRO" as a "PERL" block (see below):
1213
1214 [% MACRO triple(n) PERL %]
1215 my $n = $stash->get('n');
1216 print $n * 3;
1217 [% END -%]
1218
1219 PERL
1220 (for the advanced reader)
1221
1222 The "PERL" directive is used to mark the start of a block which
1223 contains Perl code for evaluation. The "EVAL_PERL" option must be
1224 enabled for Perl code to be evaluated or a "perl" exception will be
1225 thrown with the message '"EVAL_PERL not set"'.
1226
1227 Perl code is evaluated in the "Template::Perl" package. The $context
1228 package variable contains a reference to the current Template::Context
1229 object. This can be used to access the functionality of the Template
1230 Toolkit to process other templates, load plugins, filters, etc. See
1231 Template::Context for further details.
1232
1233 [% PERL %]
1234 print $context->include('myfile');
1235 [% END %]
1236
1237 The $stash variable contains a reference to the top-level stash object
1238 which manages template variables. Through this, variable values can be
1239 retrieved and updated. See Template::Stash for further details.
1240
1241 [% PERL %]
1242 $stash->set(foo => 'bar');
1243 print "foo value: ", $stash->get('foo');
1244 [% END %]
1245
1246 Output:
1247
1248 foo value: bar
1249
1250 Output is generated from the "PERL" block by calling "print()". Note
1251 that the "Template::Perl::PERLOUT" handle is selected (tied to an
1252 output buffer) instead of "STDOUT".
1253
1254 [% PERL %]
1255 print "foo\n"; # OK
1256 print PERLOUT "bar\n"; # OK, same as above
1257 print Template::Perl::PERLOUT "baz\n"; # OK, same as above
1258 print STDOUT "qux\n"; # WRONG!
1259 [% END %]
1260
1261 The "PERL" block may contain other template directives. These are
1262 processed before the Perl code is evaluated.
1263
1264 [% name = 'Fred Smith' %]
1265
1266 [% PERL %]
1267 print "[% name %]\n";
1268 [% END %]
1269
1270 Thus, the Perl code in the above example is evaluated as:
1271
1272 print "Fred Smith\n";
1273
1274 Exceptions may be thrown from within "PERL" blocks using "die()". They
1275 will be correctly caught by enclosing "TRY" blocks.
1276
1277 [% TRY %]
1278 [% PERL %]
1279 die "nothing to live for\n";
1280 [% END %]
1281 [% CATCH %]
1282 error: [% error.info %]
1283 [% END %]
1284
1285 output:
1286 error: nothing to live for
1287
1288 RAWPERL
1289 (for the very advanced reader)
1290
1291 The Template Toolkit parser reads a source template and generates the
1292 text of a Perl subroutine as output. It then uses "eval()" to evaluate
1293 it into a subroutine reference. This subroutine is then called to
1294 process the template, passing a reference to the current
1295 Template::Context object through which the functionality of the
1296 Template Toolkit can be accessed. The subroutine reference can be
1297 cached, allowing the template to be processed repeatedly without
1298 requiring any further parsing.
1299
1300 For example, a template such as:
1301
1302 [% PROCESS header %]
1303 The [% animal %] sat on the [% location %]
1304 [% PROCESS footer %]
1305
1306 is converted into the following Perl subroutine definition:
1307
1308 sub {
1309 my $context = shift;
1310 my $stash = $context->stash;
1311 my $output = '';
1312 my $error;
1313
1314 eval { BLOCK: {
1315 $output .= $context->process('header');
1316 $output .= "The ";
1317 $output .= $stash->get('animal');
1318 $output .= " sat on the ";
1319 $output .= $stash->get('location');
1320 $output .= $context->process('footer');
1321 $output .= "\n";
1322 } };
1323 if ($@) {
1324 $error = $context->catch($@, \$output);
1325 die $error unless $error->type eq 'return';
1326 }
1327
1328 return $output;
1329 }
1330
1331 To examine the Perl code generated, such as in the above example, set
1332 the $Template::Parser::DEBUG package variable to any true value. You
1333 can also set the $Template::Directive::PRETTY variable true to have the
1334 code formatted in a readable manner for human consumption. The source
1335 code for each generated template subroutine will be printed to "STDERR"
1336 on compilation (i.e. the first time a template is used).
1337
1338 $Template::Parser::DEBUG = 1;
1339 $Template::Directive::PRETTY = 1;
1340
1341 $template->process($file, $vars)
1342 || die $template->error(), "\n";
1343
1344 The "PERL" ... "END" construct allows Perl code to be embedded into a
1345 template when the "EVAL_PERL" option is set. It is evaluated at
1346 "runtime" using "eval()" each time the template subroutine is called.
1347 This is inherently flexible, but not as efficient as it could be,
1348 especially in a persistent server environment where a template may be
1349 processed many times.
1350
1351 The "RAWPERL" directive allows you to write Perl code that is
1352 integrated directly into the generated Perl subroutine text. It is
1353 evaluated once at compile time and is stored in cached form as part of
1354 the compiled template subroutine. This makes "RAWPERL" blocks more
1355 efficient than "PERL" blocks.
1356
1357 The downside is that you must code much closer to the metal. For
1358 example, in a "PERL" block you can call print() to generate some
1359 output. "RAWPERL" blocks don't afford such luxury. The code is inserted
1360 directly into the generated subroutine text and should conform to the
1361 convention of appending to the $output variable.
1362
1363 [% PROCESS header %]
1364
1365 [% RAWPERL %]
1366 $output .= "Some output\n";
1367 ...
1368 $output .= "Some more output\n";
1369 [% END %]
1370
1371 The critical section of the generated subroutine for this example would
1372 then look something like:
1373
1374 ...
1375 eval { BLOCK: {
1376 $output .= $context->process('header');
1377 $output .= "\n";
1378 $output .= "Some output\n";
1379 ...
1380 $output .= "Some more output\n";
1381 $output .= "\n";
1382 } };
1383 ...
1384
1385 As with "PERL" blocks, the $context and $stash references are pre-
1386 defined and available for use within "RAWPERL" code.
1387
1389 TRY / THROW / CATCH / FINAL
1390 (more advanced material)
1391
1392 The Template Toolkit supports fully functional, nested exception
1393 handling. The "TRY" directive introduces an exception handling scope
1394 which continues until the matching "END" directive. Any errors that
1395 occur within that block will be caught and can be handled by one of the
1396 "CATCH" blocks defined.
1397
1398 [% TRY %]
1399 ...blah...blah...
1400 [% CALL somecode %]
1401 ...etc...
1402 [% INCLUDE someblock %]
1403 ...and so on...
1404 [% CATCH %]
1405 An error occurred!
1406 [% END %]
1407
1408 Errors are raised as exceptions (objects of the Template::Exception
1409 class) which contain two fields: "type" and "info". The exception
1410 "type" is used to indicate the kind of error that occurred. It is a
1411 simple text string which can contain letters, numbers, '"_"' or '"."'.
1412 The "info" field contains an error message indicating what actually
1413 went wrong. Within a catch block, the exception object is aliased to
1414 the "error" variable. You can access the "type" and "info" fields
1415 directly.
1416
1417 [% mydsn = 'dbi:MySQL:foobar' %]
1418 ...
1419
1420 [% TRY %]
1421 [% USE DBI(mydsn) %]
1422 [% CATCH %]
1423 ERROR! Type: [% error.type %]
1424 Info: [% error.info %]
1425 [% END %]
1426
1427 output (assuming a non-existent database called '"foobar"'):
1428
1429 ERROR! Type: DBI
1430 Info: Unknown database "foobar"
1431
1432 The "error" variable can also be specified by itself and will return a
1433 string of the form ""$type error - $info"".
1434
1435 ...
1436 [% CATCH %]
1437 ERROR: [% error %]
1438 [% END %]
1439
1440 Output:
1441
1442 ERROR: DBI error - Unknown database "foobar"
1443
1444 Each "CATCH" block may be specified with a particular exception type
1445 denoting the kind of error that it should catch. Multiple "CATCH"
1446 blocks can be provided to handle different types of exception that may
1447 be thrown in the "TRY" block. A "CATCH" block specified without any
1448 type, as in the previous example, is a default handler which will catch
1449 any otherwise uncaught exceptions. This can also be specified as "[%
1450 CATCH DEFAULT %]".
1451
1452 [% TRY %]
1453 [% INCLUDE myfile %]
1454 [% USE DBI(mydsn) %]
1455 [% CALL somecode %]
1456 [% CATCH file %]
1457 File Error! [% error.info %]
1458 [% CATCH DBI %]
1459 [% INCLUDE database/error.html %]
1460 [% CATCH %]
1461 [% error %]
1462 [% END %]
1463
1464 Remember that you can specify multiple directives within a single tag,
1465 each delimited by '";"'. So the above example can be written more
1466 concisely as:
1467
1468 [% TRY;
1469 INCLUDE myfile;
1470 USE DBI(mydsn);
1471 CALL somecode;
1472 CATCH file;
1473 "File Error! $error.info";
1474 CATCH DBI;
1475 INCLUDE database/error.html;
1476 CATCH;
1477 error;
1478 END
1479 %]
1480
1481 The "DBI" plugin throws exceptions of the "DBI" type (in case that
1482 wasn't already obvious). The other specific exception caught here is
1483 of the "file" type.
1484
1485 A "file" exception is automatically thrown by the Template Toolkit when
1486 it can't find a file, or fails to load, parse or process a file that
1487 has been requested by an "INCLUDE", "PROCESS", "INSERT" or "WRAPPER"
1488 directive. If "myfile" can't be found in the example above, the "[%
1489 INCLUDE myfile %]" directive will raise a "file" exception which is
1490 then caught by the "[% CATCH file %]" block. The output generated
1491 would be:
1492
1493 File Error! myfile: not found
1494
1495 Note that the "DEFAULT" option (disabled by default) allows you to
1496 specify a default file to be used any time a template file can't be
1497 found. This will prevent file exceptions from ever being raised when a
1498 non-existent file is requested (unless, of course, the "DEFAULT" file
1499 your specify doesn't exist). Errors encountered once the file has been
1500 found (i.e. read error, parse error) will be raised as file exceptions
1501 as per usual.
1502
1503 Uncaught exceptions (i.e. if the "TRY" block doesn't have a type
1504 specific or default "CATCH" handler) may be caught by enclosing "TRY"
1505 blocks which can be nested indefinitely across multiple templates. If
1506 the error isn't caught at any level then processing will stop and the
1507 Template process() method will return a false value to the caller. The
1508 relevant Template::Exception object can be retrieved by calling the
1509 error() method.
1510
1511 [% TRY %]
1512 ...
1513 [% TRY %]
1514 [% INCLUDE $user.header %]
1515 [% CATCH file %]
1516 [% INCLUDE header %]
1517 [% END %]
1518 ...
1519 [% CATCH DBI %]
1520 [% INCLUDE database/error.html %]
1521 [% END %]
1522
1523 In this example, the inner "TRY" block is used to ensure that the first
1524 "INCLUDE" directive works as expected. We're using a variable to
1525 provide the name of the template we want to include, "user.header", and
1526 it's possible this contains the name of a non-existent template, or
1527 perhaps one containing invalid template directives. If the "INCLUDE"
1528 fails with a "file" error then we "CATCH" it in the inner block and
1529 "INCLUDE" the default "header" file instead. Any "DBI" errors that
1530 occur within the scope of the outer "TRY" block will be caught in the
1531 relevant "CATCH" block, causing the "database/error.html" template to
1532 be processed. Note that included templates inherit all currently
1533 defined template variable so these error files can quite happily access
1534 the <error> variable to retrieve information about the currently caught
1535 exception. For example, the "database/error.html" template might look
1536 like this:
1537
1538 <h2>Database Error</h2>
1539 A database error has occurred: [% error.info %]
1540
1541 You can also specify a "FINAL" block. This is always processed
1542 regardless of the outcome of the "TRY" and/or "CATCH" blocks. If an
1543 exception is uncaught then the "FINAL" block is processed before
1544 jumping to the enclosing block or returning to the caller.
1545
1546 [% TRY %]
1547 ...
1548 [% CATCH this %]
1549 ...
1550 [% CATCH that %]
1551 ...
1552 [% FINAL %]
1553 All done!
1554 [% END %]
1555
1556 The output from the "TRY" block is left intact up to the point where an
1557 exception occurs. For example, this template:
1558
1559 [% TRY %]
1560 This gets printed
1561 [% THROW food 'carrots' %]
1562 This doesn't
1563 [% CATCH food %]
1564 culinary delights: [% error.info %]
1565 [% END %]
1566
1567 generates the following output:
1568
1569 This gets printed
1570 culinary delights: carrots
1571
1572 The "CLEAR" directive can be used in a "CATCH" or "FINAL" block to
1573 clear any output created in the "TRY" block.
1574
1575 [% TRY %]
1576 This gets printed
1577 [% THROW food 'carrots' %]
1578 This doesn't
1579 [% CATCH food %]
1580 [% CLEAR %]
1581 culinary delights: [% error.info %]
1582 [% END %]
1583
1584 Output:
1585
1586 culinary delights: carrots
1587
1588 Exception types are hierarchical, with each level being separated by
1589 the familiar dot operator. A "DBI.connect" exception is a more
1590 specific kind of "DBI" error. Similarly, an "example.error.barf" is a
1591 more specific kind of "example.error" type which itself is also a
1592 "example" error.
1593
1594 A "CATCH" handler that specifies a general exception type (such as
1595 "DBI" or "example.error") will also catch more specific types that have
1596 the same prefix as long as a more specific handler isn't defined. Note
1597 that the order in which "CATCH" handlers are defined is irrelevant; a
1598 more specific handler will always catch an exception in preference to a
1599 more generic or default one.
1600
1601 [% TRY %]
1602 ...
1603 [% CATCH DBI ;
1604 INCLUDE database/error.html ;
1605 CATCH DBI.connect ;
1606 INCLUDE database/connect.html ;
1607 CATCH ;
1608 INCLUDE error.html ;
1609 END
1610 %]
1611
1612 In this example, a "DBI.connect" error has it's own handler, a more
1613 general "DBI" block is used for all other "DBI" or "DBI.*" errors and a
1614 default handler catches everything else.
1615
1616 Exceptions can be raised in a template using the "THROW" directive.
1617 The first parameter is the exception type which doesn't need to be
1618 quoted (but can be, it's the same as "INCLUDE") followed by the
1619 relevant error message which can be any regular value such as a quoted
1620 string, variable, etc.
1621
1622 [% THROW food "Missing ingredients: $recipe.error" %]
1623 [% THROW user.login 'no user id: please login' %]
1624 [% THROW $myerror.type "My Error: $myerror.info" %]
1625
1626 It's also possible to specify additional positional or named parameters
1627 to the "THROW" directive if you want to pass more than just a simple
1628 message back as the error info field.
1629
1630 [% THROW food 'eggs' 'flour' msg='Missing Ingredients' %]
1631
1632 In this case, the error "info" field will be a hash array containing
1633 the named arguments and an "args" item which contains a list of the
1634 positional arguments.
1635
1636 type => 'food',
1637 info => {
1638 msg => 'Missing Ingredients',
1639 args => ['eggs', 'flour'],
1640 }
1641
1642 In addition to specifying individual positional arguments as "[%
1643 error.info.args.n %]", the "info" hash contains keys directly pointing
1644 to the positional arguments, as a convenient shortcut.
1645
1646 [% error.info.0 %] # same as [% error.info.args.0 %]
1647
1648 Exceptions can also be thrown from Perl code which you've bound to
1649 template variables, or defined as a plugin or other extension. To
1650 raise an exception, call "die()" passing a reference to a
1651 Template::Exception object as the argument. This will then be caught
1652 by any enclosing "TRY" blocks from where the code was called.
1653
1654 use Template::Exception;
1655 ...
1656 my $vars = {
1657 foo => sub {
1658 # ... do something ...
1659 die Template::Exception->new('myerr.naughty',
1660 'Bad, bad error');
1661 },
1662 };
1663
1664 Template:
1665
1666 [% TRY %]
1667 [% foo %]
1668 [% CATCH myerr ;
1669 "Error: $error" ;
1670 END
1671 %]
1672
1673 Output:
1674
1675 Error: myerr.naughty error - Bad, bad error
1676
1677 The "info" field can also be a reference to another object or data
1678 structure, if required.
1679
1680 die Template::Exception->new('myerror', {
1681 module => 'foo.pl',
1682 errors => [ 'bad permissions', 'naughty boy' ],
1683 });
1684
1685 Later, in a template:
1686
1687 [% TRY %]
1688 ...
1689 [% CATCH myerror %]
1690 [% error.info.errors.size or 'no';
1691 error.info.errors.size == 1 ? ' error' : ' errors' %]
1692 in [% error.info.module %]:
1693 [% error.info.errors.join(', ') %].
1694 [% END %]
1695
1696 Generating the output:
1697
1698 2 errors in foo.pl:
1699 bad permissions, naughty boy.
1700
1701 You can also call "die()" with a single string, as is common in much
1702 existing Perl code. This will automatically be converted to an
1703 exception of the '"undef"' type (that's the literal string '"undef"',
1704 not the undefined value). If the string isn't terminated with a
1705 newline then Perl will append the familiar " at $file line $line"
1706 message.
1707
1708 sub foo {
1709 # ... do something ...
1710 die "I'm sorry, Dave, I can't do that\n";
1711 }
1712
1713 If you're writing a plugin, or some extension code that has the current
1714 Template::Context in scope (you can safely skip this section if this
1715 means nothing to you) then you can also raise an exception by calling
1716 the context throw() method. You can pass it an Template::Exception
1717 object reference, a pair of "($type, $info)" parameters or just an
1718 $info string to create an exception of '"undef"' type.
1719
1720 $context->throw($e); # exception object
1721 $context->throw('Denied'); # 'undef' type
1722 $context->throw('user.passwd', 'Bad Password');
1723
1724 NEXT
1725 The "NEXT" directive can be used to start the next iteration of a
1726 "FOREACH" or "WHILE" loop.
1727
1728 [% FOREACH user IN users %]
1729 [% NEXT IF user.isguest %]
1730 Name: [% user.name %] Email: [% user.email %]
1731 [% END %]
1732
1733 LAST
1734 The "LAST" directive can be used to prematurely exit a "FOREACH" or
1735 "WHILE" loop.
1736
1737 [% FOREACH user IN users %]
1738 Name: [% user.name %] Email: [% user.email %]
1739 [% LAST IF some.condition %]
1740 [% END %]
1741
1742 "BREAK" can also be used as an alias for "LAST".
1743
1744 RETURN
1745 The "RETURN" directive can be used to stop processing the current
1746 template and return to the template from which it was called, resuming
1747 processing at the point immediately after the "INCLUDE", "PROCESS" or
1748 "WRAPPER" directive. If there is no enclosing template then the
1749 Template process() method will return to the calling code with a true
1750 value.
1751
1752 Before
1753 [% INCLUDE half_wit %]
1754 After
1755
1756 [% BLOCK half_wit %]
1757 This is just half...
1758 [% RETURN %]
1759 ...a complete block
1760 [% END %]
1761
1762 Output:
1763
1764 Before
1765 This is just half...
1766 After
1767
1768 STOP
1769 The "STOP" directive can be used to indicate that the processor should
1770 stop gracefully without processing any more of the template document.
1771 This is a planned stop and the Template process() method will return a
1772 true value to the caller. This indicates that the template was
1773 processed successfully according to the directives within it.
1774
1775 [% IF something.terrible.happened %]
1776 [% INCLUDE fatal/error.html %]
1777 [% STOP %]
1778 [% END %]
1779
1780 [% TRY %]
1781 [% USE DBI(mydsn) %]
1782 ...
1783 [% CATCH DBI.connect %]
1784 <h1>Cannot connect to the database: [% error.info %]</h1>
1785 <p>
1786 We apologise for the inconvenience.
1787 </p>
1788 [% INCLUDE footer %]
1789 [% STOP %]
1790 [% END %]
1791
1792 CLEAR
1793 The "CLEAR" directive can be used to clear the output buffer for the
1794 current enclosing block. It is most commonly used to clear the output
1795 generated from a "TRY" block up to the point where the error occurred.
1796
1797 [% TRY %]
1798 blah blah blah # this is normally left intact
1799 [% THROW some 'error' %] # up to the point of error
1800 ...
1801 [% CATCH %]
1802 [% CLEAR %] # clear the TRY output
1803 [% error %] # print error string
1804 [% END %]
1805
1807 META
1808 The "META" directive allows simple metadata items to be defined within
1809 a template. These are evaluated when the template is parsed and as such
1810 may only contain simple values (e.g. it's not possible to interpolate
1811 other variables values into "META" variables).
1812
1813 [% META
1814 title = 'The Cat in the Hat'
1815 author = 'Dr. Seuss'
1816 version = 1.23
1817 %]
1818
1819 The "template" variable contains a reference to the main template being
1820 processed. These metadata items may be retrieved as attributes of the
1821 template.
1822
1823 <h1>[% template.title %]</h1>
1824 <h2>[% template.author %]</h2>
1825
1826 The "name" and "modtime" metadata items are automatically defined for
1827 each template to contain its name and modification time in seconds
1828 since the epoch.
1829
1830 [% USE date %] # use Date plugin to format time
1831 ...
1832 [% template.name %] last modified
1833 at [% date.format(template.modtime) %]
1834
1835 The "PRE_PROCESS" and "POST_PROCESS" options allow common headers and
1836 footers to be added to all templates. The "template" reference is
1837 correctly defined when these templates are processed, allowing headers
1838 and footers to reference metadata items from the main template.
1839
1840 $template = Template->new({
1841 PRE_PROCESS => 'header',
1842 POST_PROCESS => 'footer',
1843 });
1844
1845 $template->process('cat_in_hat');
1846
1847 header:
1848
1849 <html>
1850 <head>
1851 <title>[% template.title %]</title>
1852 </head>
1853 <body>
1854
1855 cat_in_hat:
1856
1857 [% META
1858 title = 'The Cat in the Hat'
1859 author = 'Dr. Seuss'
1860 version = 1.23
1861 year = 2000
1862 %]
1863
1864 The cat in the hat sat on the mat.
1865
1866 footer:
1867
1868 <hr>
1869 © [% template.year %] [% template.author %]
1870 </body>
1871 </html>
1872
1873 The output generated from the above example is:
1874
1875 <html>
1876 <head>
1877 <title>The Cat in the Hat</title>
1878 </head>
1879 <body>
1880 The cat in the hat sat on the mat.
1881 <hr>
1882 © 2000 Dr. Seuss
1883 </body>
1884 </html>
1885
1886 TAGS
1887 The "TAGS" directive can be used to set the "START_TAG" and "END_TAG"
1888 values on a per-template file basis.
1889
1890 [% TAGS <+ +> %]
1891
1892 <+ INCLUDE header +>
1893
1894 The TAGS directive may also be used to set a named "TAG_STYLE"
1895
1896 [% TAGS html %]
1897 <!-- INCLUDE header -->
1898
1899 See the TAGS and TAG_STYLE configuration options for further details.
1900
1901 DEBUG
1902 The "DEBUG" directive can be used to enable or disable directive debug
1903 messages within a template. The "DEBUG" configuration option must be
1904 set to include "DEBUG_DIRS" for the "DEBUG" directives to have any
1905 effect. If "DEBUG_DIRS" is not set then the parser will automatically
1906 ignore and remove any "DEBUG" directives.
1907
1908 The "DEBUG" directive can be used with an "on" or "off" parameter to
1909 enable or disable directive debugging messages from that point forward.
1910 When enabled, the output of each directive in the generated output will
1911 be prefixed by a comment indicate the file, line and original directive
1912 text.
1913
1914 [% DEBUG on %]
1915 directive debugging is on (assuming DEBUG option is set true)
1916 [% DEBUG off %]
1917 directive debugging is off
1918
1919 The "format" parameter can be used to change the format of the
1920 debugging message.
1921
1922 [% DEBUG format '<!-- $file line $line : [% $text %] -->' %]
1923
1924
1925
1926perl v5.30.1 2020-01-30 Template::Manual::Directives(3)