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