1Template::Manual::VariaUbsleers(C3o)ntributed Perl DocumTeenmtpaltaitoen::Manual::Variables(3)
2
3
4
6 Template::Manual::Variables - Template variables and code bindings
7
9 A reference to a hash array may be passed as the second argument to the
10 process() method, containing definitions of template variables. The
11 "VARIABLES" (a.k.a. "PRE_DEFINE") option can also be used to pre-define
12 variables for all templates processed by the object.
13
14 my $tt = Template->new({
15 VARIABLES => {
16 version => 3.14,
17 release => 'Sahara',
18 },
19 });
20
21 my $vars = {
22 serial_no => 271828,
23 };
24
25 $tt->process('myfile', $vars);
26
27 myfile template:
28
29 This is version [% version %] ([% release %]).
30 Serial number: [% serial_no %]
31
32 Generated Output:
33
34 This is version 3.14 (Sahara)
35 Serial number: 271828
36
37 Variable names may contain any alphanumeric characters or underscores.
38 They may be lower, upper or mixed case although the usual convention is
39 to use lower case. The case is significant however, and '"foo"',
40 '"Foo"' and '"FOO"' are all different variables. Upper case variable
41 names are permitted, but not recommended due to a possible conflict
42 with an existing or future reserved word. As of version 2.00, these
43 are:
44
45 GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER
46 IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
47 USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
48 TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP
49 CLEAR TO STEP AND OR NOT MOD DIV END
50
51 The variable values may be of virtually any Perl type, including simple
52 scalars, references to lists, hash arrays, subroutines or objects. The
53 Template Toolkit will automatically apply the correct procedure to
54 accessing these values as they are used in the template.
55
56 Example data:
57
58 my $vars = {
59 article => 'The Third Shoe',
60 person => {
61 id => 314,
62 name => 'Mr. Blue',
63 email => 'blue@nowhere.org',
64 },
65 primes => [ 2, 3, 5, 7, 11, 13 ],
66 wizard => sub { return join(' ', 'Abracadabra!', @_) },
67 cgi => CGI->new('mode=submit&debug=1'),
68 };
69
70 Example template:
71
72 [% article %]
73
74 [% person.id %]: [% person.name %] <[% person.email %]>
75
76 [% primes.first %] - [% primes.last %], including [% primes.3 %]
77 [% primes.size %] prime numbers: [% primes.join(', ') %]
78
79 [% wizard %]
80 [% wizard('Hocus Pocus!') %]
81
82 [% cgi.param('mode') %]
83
84 Generated output:
85
86 The Third Shoe
87
88 314: Mr. Blue <blue@nowhere.org>
89
90 2 - 13, including 7
91 6 prime numbers: 2, 3, 5, 7, 11, 13
92
93 Abracadabra!
94 Abracadabra! Hocus Pocus!
95
96 submit
97
98 Scalar Values
99 Regular scalar variables are accessed by simply specifying their name.
100 As these are just entries in the top-level variable hash they can be
101 considered special cases of hash array referencing as described below,
102 with the main namespace hash automatically implied.
103
104 [% article %]
105
106 Hash Array References
107 Members of hash arrays are accessed by specifying the hash reference
108 and key separated by the dot '"."' operator.
109
110 Example data:
111
112 my $vars = {
113 'home' => 'http://www.myserver.com/homepage.html',
114 'page' => {
115 'this' => 'mypage.html',
116 'next' => 'nextpage.html',
117 'prev' => 'prevpage.html',
118 },
119 };
120
121 Example template:
122
123 <a href="[% home %]">Home</a>
124 <a href="[% page.prev %]">Previous Page</a>
125 <a href="[% page.next %]">Next Page</a>
126
127 Generated output:
128
129 <a href="http://www.myserver.com/homepage.html">Home</a>
130 <a href="prevpage.html">Previous Page</a>
131 <a href="nextpage.html">Next Page</a>
132
133 Any key in a hash which starts with a '"_"' or '"."' character will be
134 considered private and cannot be evaluated or updated from within a
135 template. The undefined value will be returned for any such variable
136 accessed which the Template Toolkit will silently ignore (unless the
137 "DEBUG" option is enabled).
138
139 Example data:
140
141 my $vars = {
142 message => 'Hello World!',
143 _secret => "On the Internet, no-one knows you're a dog",
144 thing => {
145 public => 123,
146 _private => 456,
147 '.hidden' => 789,
148 },
149 };
150
151 Example template:
152
153 [% message %] # outputs "Hello World!"
154 [% _secret %] # no output
155 [% thing.public %] # outputs "123"
156 [% thing._private %] # no output
157 [% thing..hidden %] # ERROR: unexpected token (..)
158
159 You can disable this feature by setting the $Template::Stash::PRIVATE
160 package variable to a false value.
161
162 $Template::Stash::PRIVATE = undef; # now you can thing._private
163
164 To access a hash entry using a key stored in another variable, prefix
165 the key variable with '"$"' to have it interpolated before use (see
166 "Variable Interpolation").
167
168 [% pagename = 'next' %]
169 [% page.$pagename %] # same as [% page.next %]
170
171 When you assign to a variable that contains multiple namespace elements
172 (i.e. it has one or more '"."' characters in the name), any hashes
173 required to represent intermediate namespaces will be created
174 automatically. In this following example, the "product" variable
175 automatically springs into life as a hash array unless otherwise
176 defined.
177
178 [% product.id = 'XYZ-2000'
179 product.desc = 'Bogon Generator'
180 product.price = 666
181 %]
182
183 The [% product.id %] [% product.desc %]
184 costs $[% product.price %].00
185
186 Generated output:
187
188 The XYZ-2000 Bogon Generator
189 costs $666.00
190
191 You can use Perl's familiar "{" ... "}" construct to explicitly create
192 a hash and assign it to a variable. Note that commas are optional
193 between key/value pairs and "=" can be used in place of "=>".
194
195 # minimal TT style
196 [% product = {
197 id = 'XYZ-2000'
198 desc = 'Bogon Generator'
199 price = 666
200 }
201 %]
202
203 # perl style
204 [% product = {
205 id => 'XYZ-2000',
206 desc => 'Bogon Generator',
207 price => 666,
208 }
209 %]
210
211 List References
212 Items in lists are also accessed by use of the dot operator.
213
214 Example data:
215
216 my $vars = {
217 people => [ 'Tom', 'Dick', 'Larry' ],
218 };
219
220 Example template:
221
222 [% people.0 %] # Tom
223 [% people.1 %] # Dick
224 [% people.2 %] # Larry
225
226 The "FOREACH" directive can be used to iterate through items in a list.
227
228 [% FOREACH person IN people %]
229 Hello [% person %]
230 [% END %]
231
232 Generated output:
233
234 Hello Tom
235 Hello Dick
236 Hello Larry
237
238 Lists can be constructed in-situ using the regular anonymous list "["
239 ... "]" construct. Commas between items are optional.
240
241 [% cols = [ 'red', 'green', 'blue' ] %]
242
243 [% FOREACH c IN cols %]
244 [% c %]
245 [% END %]
246
247 or:
248
249 [% FOREACH c IN [ 'red', 'green', 'blue' ] %]
250 [% c %]
251 [% END %]
252
253 You can also create simple numerical sequences using the ".." range
254 operator:
255
256 [% n = [ 1 .. 4 ] %] # n is [ 1, 2, 3, 4 ]
257
258 [% x = 4
259 y = 8
260 z = [x..y] # z is [ 4, 5, 6, 7, 8 ]
261 %]
262
263 Subroutines
264 Template variables can contain references to Perl subroutines. When
265 the variable is used, the Template Toolkit will automatically call the
266 subroutine, passing any additional arguments specified. The return
267 value from the subroutine is used as the variable value and inserted
268 into the document output.
269
270 my $vars = {
271 wizard => sub { return join(' ', 'Abracadabra!', @_) },
272 };
273
274 Example template:
275
276 [% wizard %] # Abracadabra!
277 [% wizard('Hocus Pocus!') %] # Abracadabra! Hocus Pocus!
278
279 Objects
280 Template variables can also contain references to Perl objects.
281 Methods are called using the dot operator to specify the method against
282 the object variable. Additional arguments can be specified as with
283 subroutines.
284
285 use CGI;
286
287 my $vars = {
288 # hard coded CGI params for purpose of example
289 cgi => CGI->new('mode=submit&debug=1'),
290 };
291
292 Example template:
293
294 [% FOREACH p IN cgi.param %] # returns list of param keys
295 [% p %] => [% cgi.param(p) %] # fetch each param value
296 [% END %]
297
298 Generated output:
299
300 mode => submit
301 debug => 1
302
303 Object methods can also be called as lvalues. That is, they can appear
304 on the left side of an assignment. The method will be called passing
305 the assigning value as an argument.
306
307 [% myobj.method = 10 %]
308
309 equivalent to:
310
311 [% myobj.method(10) %]
312
313 Passing Parameters and Returning Values
314 Subroutines and methods will be passed any arguments specified in the
315 template. Any template variables in the argument list will first be
316 evaluated and their resultant values passed to the code.
317
318 my $vars = {
319 mycode => sub { return 'received ' . join(', ', @_) },
320 };
321
322 template:
323
324 [% foo = 10 %]
325 [% mycode(foo, 20) %] # received 10, 20
326
327 Named parameters may also be specified. These are automatically
328 collected into a single hash array which is passed by reference as the
329 last parameter to the sub-routine. Named parameters can be specified
330 using either "=>" or "=" and can appear anywhere in the argument list.
331
332 my $vars = {
333 myjoin => \&myjoin,
334 };
335
336 sub myjoin {
337 # look for hash ref as last argument
338 my $params = ref $_[-1] eq 'HASH' ? pop : { };
339 return join($params->{ joint } || ' + ', @_);
340 }
341
342 Example template:
343
344 [% myjoin(10, 20, 30) %]
345 [% myjoin(10, 20, 30, joint = ' - ' %]
346 [% myjoin(joint => ' * ', 10, 20, 30 %]
347
348 Generated output:
349
350 10 + 20 + 30
351 10 - 20 - 30
352 10 * 20 * 30
353
354 Parenthesised parameters may be added to any element of a variable, not
355 just those that are bound to code or object methods. At present,
356 parameters will be ignored if the variable isn't "callable" but are
357 supported for future extensions. Think of them as "hints" to that
358 variable, rather than just arguments passed to a function.
359
360 [% r = 'Romeo' %]
361 [% r(100, 99, s, t, v) %] # outputs "Romeo"
362
363 User code should return a value for the variable it represents. This
364 can be any of the Perl data types described above: a scalar, or
365 reference to a list, hash, subroutine or object. Where code returns a
366 list of multiple values the items will automatically be folded into a
367 list reference which can be accessed as per normal.
368
369 my $vars = {
370 # either is OK, first is recommended
371 items1 => sub { return [ 'foo', 'bar', 'baz' ] },
372 items2 => sub { return ( 'foo', 'bar', 'baz' ) },
373 };
374
375 Example template:
376
377 [% FOREACH i IN items1 %]
378 ...
379 [% END %]
380
381 [% FOREACH i IN items2 %]
382 ...
383 [% END %]
384
385 Error Handling
386 Errors can be reported from user code by calling "die()". Errors
387 raised in this way are caught by the Template Toolkit and converted to
388 structured exceptions which can be handled from within the template. A
389 reference to the exception object is then available as the "error"
390 variable.
391
392 my $vars = {
393 barf => sub {
394 die "a sick error has occurred\n";
395 },
396 };
397
398 Example template:
399
400 [% TRY %]
401 [% barf %] # calls sub which throws error via die()
402 [% CATCH %]
403 [% error.info %] # outputs "a sick error has occurred\n"
404 [% END %]
405
406 Error messages thrown via "die()" are converted to exceptions of type
407 "undef" (the literal string "undef" rather than the undefined value).
408 Exceptions of user-defined types can be thrown by calling "die()" with
409 a reference to a Template::Exception object.
410
411 use Template::Exception;
412
413 my $vars = {
414 login => sub {
415 ...do something...
416 die Template::Exception->new( badpwd => 'password too silly' );
417 },
418 };
419
420 Example template:
421
422 [% TRY %]
423 [% login %]
424 [% CATCH badpwd %]
425 Bad password: [% error.info %]
426 [% CATCH %]
427 Some other '[% error.type %]' error: [% error.info %]
428 [% END %]
429
430 The exception types "stop" and "return" are used to implement the
431 "STOP" and "RETURN" directives. Throwing an exception as:
432
433 die (Template::Exception->new('stop'));
434
435 has the same effect as the directive:
436
437 [% STOP %]
438
440 The Template Toolkit implements a number of "virtual methods" which can
441 be applied to scalars, hashes or lists. For example:
442
443 [% mylist = [ 'foo', 'bar', 'baz' ] %]
444 [% newlist = mylist.sort %]
445
446 Here "mylist" is a regular reference to a list, and 'sort' is a virtual
447 method that returns a new list of the items in sorted order. You can
448 chain multiple virtual methods together. For example:
449
450 [% mylist.sort.join(', ') %]
451
452 Here the "join" virtual method is called to join the sorted list into a
453 single string, generating the following output:
454
455 bar, baz, foo
456
457 See Template::Manual::VMethods for details of all the virtual methods
458 available.
459
461 The Template Toolkit uses "$" consistently to indicate that a variable
462 should be interpolated in position. Most frequently, you see this in
463 double-quoted strings:
464
465 [% fullname = "$honorific $firstname $surname" %]
466
467 Or embedded in plain text when the "INTERPOLATE" option is set:
468
469 Dear $honorific $firstname $surname,
470
471 The same rules apply within directives. If a variable is prefixed with
472 a "$" then it is replaced with its value before being used. The most
473 common use is to retrieve an element from a hash where the key is
474 stored in a variable.
475
476 [% uid = 'abw' %]
477 [% users.$uid %] # same as 'userlist.abw'
478
479 Curly braces can be used to delimit interpolated variable names where
480 necessary.
481
482 [% users.${me.id}.name %]
483
484 Directives such as "INCLUDE", "PROCESS", etc., that accept a template
485 name as the first argument, will automatically quote it for
486 convenience.
487
488 [% INCLUDE foo/bar.txt %]
489
490 The above example is equivalent to:
491
492 [% INCLUDE "foo/bar.txt" %]
493
494 To "INCLUDE" a template whose name is stored in a variable, simply
495 prefix the variable name with "$" to have it interpolated.
496
497 [% myfile = 'header' %]
498 [% INCLUDE $myfile %]
499
500 This is equivalent to:
501
502 [% INCLUDE header %]
503
504 Note also that a variable containing a reference to a
505 Template::Document object can also be processed in this way.
506
507 my $vars = {
508 header => Template::Document->new({ ... }),
509 };
510
511 Example template:
512
513 [% INCLUDE $header %]
514
516 Any simple variables that you create, or any changes you make to
517 existing variables, will only persist while the template is being
518 processed. The top-level variable hash is copied before processing
519 begins and any changes to variables are made in this copy, leaving the
520 original intact.
521
522 The same thing happens when you "INCLUDE" another template. The current
523 namespace hash is cloned to prevent any variable changes made in the
524 included template from interfering with existing variables. The
525 "PROCESS" option bypasses the localisation step altogether making it
526 slightly faster, but requiring greater attention to the possibility of
527 side effects caused by creating or changing any variables within the
528 processed template.
529
530 [% BLOCK change_name %]
531 [% name = 'bar' %]
532 [% END %]
533
534 [% name = 'foo' %]
535 [% INCLUDE change_name %]
536 [% name %] # foo
537 [% PROCESS change_name %]
538 [% name %] # bar
539
540 Dotted compound variables behave slightly differently because the
541 localisation process is only skin deep. The current variable namespace
542 hash is copied, but no attempt is made to perform a deep-copy of other
543 structures within it (hashes, arrays, objects, etc). A variable
544 referencing a hash, for example, will be copied to create a new
545 reference but which points to the same hash. Thus, the general rule is
546 that simple variables (undotted variables) are localised, but existing
547 complex structures (dotted variables) are not.
548
549 [% BLOCK all_change %]
550 [% x = 20 %] # changes copy
551 [% y.z = 'zulu' %] # changes original
552 [% END %]
553
554 [% x = 10
555 y = { z => 'zebra' }
556 %]
557 [% INCLUDE all_change %]
558 [% x %] # still '10'
559 [% y.z %] # now 'zulu'
560
561 If you create a complex structure such as a hash or list reference
562 within a local template context then it will cease to exist when the
563 template is finished processing.
564
565 [% BLOCK new_stuff %]
566 [% # define a new 'y' hash array in local context
567 y = { z => 'zulu' }
568 %]
569 [% END %]
570
571 [% x = 10 %]
572 [% INCLUDE new_stuff %]
573 [% x %] # outputs '10'
574 [% y %] # nothing, y is undefined
575
576 Similarly, if you update an element of a compound variable which
577 doesn't already exists then a hash will be created automatically and
578 deleted again at the end of the block.
579
580 [% BLOCK new_stuff %]
581 [% y.z = 'zulu' %]
582 [% END %]
583
584 However, if the hash does already exist then you will modify the
585 original with permanent effect. To avoid potential confusion, it is
586 recommended that you don't update elements of complex variables from
587 within blocks or templates included by another.
588
589 If you want to create or update truly global variables then you can use
590 the 'global' namespace. This is a hash array automatically created in
591 the top-level namespace which all templates, localised or otherwise see
592 the same reference to. Changes made to variables within this hash are
593 visible across all templates.
594
595 [% global.version = 123 %]
596
598 In addition to variables that get resolved each time a template is
599 processed, you can also define variables that get resolved just once
600 when the template is compiled. This generally results in templates
601 processing faster because there is less work to be done.
602
603 To define compile-time constants, specify a "CONSTANTS" hash as a
604 constructor item as per "VARIABLES". The "CONSTANTS" hash can contain
605 any kind of complex, nested, or dynamic data structures, just like
606 regular variables.
607
608 my $tt = Template->new({
609 CONSTANTS => {
610 version => 3.14,
611 release => 'skyrocket',
612 col => {
613 back => '#ffffff',
614 fore => '#000000',
615 },
616 myobj => My::Object->new(),
617 mysub => sub { ... },
618 joint => ', ',
619 },
620 });
621
622 Within a template, you access these variables using the "constants"
623 namespace prefix.
624
625 Version [% constants.version %] ([% constants.release %])
626 Background: [% constants.col.back %]
627
628 When the template is compiled, these variable references are replaced
629 with the corresponding value. No further variable lookup is then
630 required when the template is processed.
631
632 You can call subroutines, object methods, and even virtual methods on
633 constant variables.
634
635 [% constants.mysub(10, 20) %]
636 [% constants.myobj(30, 40) %]
637 [% constants.col.keys.sort.join(', ') %]
638
639 One important proviso is that any arguments you pass to subroutines or
640 methods must also be literal values or compile time constants.
641
642 For example, these are both fine:
643
644 # literal argument
645 [% constants.col.keys.sort.join(', ') %]
646
647 # constant argument
648 [% constants.col.keys.sort.join(constants.joint) %]
649
650 But this next example will raise an error at parse time because "joint"
651 is a runtime variable and cannot be determined at compile time.
652
653 # ERROR: runtime variable argument!
654 [% constants.col.keys.sort.join(joint) %]
655
656 The "CONSTANTS_NAMESPACE" option can be used to provide a different
657 namespace prefix for constant variables. For example:
658
659 my $tt = Template->new({
660 CONSTANTS => {
661 version => 3.14,
662 # ...etc...
663 },
664 CONSTANTS_NAMESPACE => 'const',
665 });
666
667 Constants would then be referenced in templates as:
668
669 [% const.version %]
670
672 A number of special variables are automatically defined by the Template
673 Toolkit.
674
675 template
676 The "template" variable contains a reference to the main template being
677 processed, in the form of a Template::Document object. This variable is
678 correctly defined within "PRE_PROCESS", "PROCESS" and "POST_PROCESS"
679 templates, allowing standard headers, footers, etc., to access metadata
680 items from the main template. The "name" and "modtime" metadata items
681 are automatically provided, giving the template name and modification
682 time in seconds since the epoch.
683
684 Note that the "template" variable always references the top-level
685 template, even when processing other template components via "INCLUDE",
686 "PROCESS", etc.
687
688 component
689 The "component" variable is like "template" but always contains a
690 reference to the current, innermost template component being processed.
691 In the main template, the "template" and "component" variable will
692 reference the same Template::Document object. In any other template
693 component called from the main template, the "template" variable will
694 remain unchanged, but "component" will contain a new reference to the
695 current component.
696
697 This example should demonstrate the difference:
698
699 $template->process('foo')
700 || die $template->error(), "\n";
701
702 foo template:
703
704 [% template.name %] # foo
705 [% component.name %] # foo
706 [% PROCESS footer %]
707
708 footer template:
709
710 [% template.name %] # foo
711 [% component.name %] # footer
712
713 Additionally, the "component" variable has two special fields: "caller"
714 and "callers". "caller" contains the name of the template that called
715 the current template (or undef if the values of "template" and
716 "component" are the same). "callers" contains a reference to a list of
717 all the templates that have been called on the road to calling the
718 current component template (like a call stack), with the outer-most
719 template first.
720
721 Here's an example:
722
723 outer.tt2 template:
724
725 [% component.name %] # 'outer.tt2'
726 [% component.caller %] # undef
727 [% component.callers %] # undef
728 [% PROCESS 'middle.tt2' %]
729
730 middle.tt2 template:
731
732 [% component.name %] # 'middle.tt2'
733 [% component.caller %] # 'outer.tt2'
734 [% component.callers %] # [ 'outer.tt2' ]
735 [% PROCESS 'inner.tt2' %]
736
737 inner.tt2 template:
738
739 [% component.name %] # 'inner.tt2'
740 [% component.caller %] # 'middle.tt2'
741 [% component.callers %] # [ 'outer.tt2', 'middle.tt2' ]
742
743 loop
744 Within a "FOREACH" loop, the "loop" variable references the
745 Template::Iterator object responsible for controlling the loop.
746
747 [% FOREACH item = [ 'foo', 'bar', 'baz' ] -%]
748 [% "Items:\n" IF loop.first -%]
749 [% loop.count %]/[% loop.size %]: [% item %]
750 [% END %]
751
752 error
753 Within a "CATCH" block, the "error" variable contains a reference to
754 the Template::Exception object thrown from within the "TRY" block. The
755 "type" and "info" methods can be called or the variable itself can be
756 printed for automatic stringification into a message of the form
757 ""$type error - $info"". See Template::Exception for further details.
758
759 [% TRY %]
760 ...
761 [% CATCH %]
762 [% error %]
763 [% END %]
764
765 content
766 The "WRAPPER" method captures the output from a template block and then
767 includes a named template, passing the captured output as the 'content'
768 variable.
769
770 [% WRAPPER box %]
771 Be not afeard; the isle is full of noises,
772 Sounds and sweet airs, that give delight and hurt not.
773 [% END %]
774
775 [% BLOCK box %]
776 <blockquote class="prose">
777 [% content %]
778 </blockquote>
779 [% END %]
780
782 Compound 'dotted' variables may contain any number of separate
783 elements. Each element may evaluate to any of the permitted variable
784 types and the processor will then correctly use this value to evaluate
785 the rest of the variable. Arguments may be passed to any of the
786 intermediate elements.
787
788 [% myorg.people.sort('surname').first.fullname %]
789
790 Intermediate variables may be used and will behave entirely as
791 expected.
792
793 [% sorted = myorg.people.sort('surname') %]
794 [% sorted.first.fullname %]
795
796 This simplified dotted notation has the benefit of hiding the
797 implementation details of your data. For example, you could implement
798 a data structure as a hash array one day and then change it to an
799 object the next without requiring any change to the templates.
800
801
802
803perl v5.30.0 2019-07-26 Template::Manual::Variables(3)