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