1 #============================================================= -*-perl-*-
3 # Template::Manual::Variables
6 # Andy Wardley <abw@wardley.org>
9 # Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
11 # This module is free software; you can redistribute it and/or
12 # modify it under the same terms as Perl itself.
14 #========================================================================
18 Template::Manual::Variables - Template variables and code bindings
20 =head1 Template Variables
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.
27 my $tt = Template->new({
38 $tt->process('myfile', $vars);
42 This is version [% version %] ([% release %]).
43 Serial number: [% serial_no %]
47 This is version 3.14 (Sahara)
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:
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
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.
71 article => 'The Third Shoe',
75 email => 'blue@nowhere.org',
77 primes => [ 2, 3, 5, 7, 11, 13 ],
78 wizard => sub { return join(' ', 'Abracadabra!', @_) },
79 cgi => CGI->new('mode=submit&debug=1'),
86 [% person.id %]: [% person.name %] <[% person.email %]>
88 [% primes.first %] - [% primes.last %], including [% primes.3 %]
89 [% primes.size %] prime numbers: [% primes.join(', ') %]
92 [% wizard('Hocus Pocus!') %]
94 [% cgi.param('mode') %]
100 314: Mr. Blue <blue@nowhere.org>
103 6 prime numbers: 2, 3, 5, 7, 11, 13
106 Abracadabra! Hocus Pocus!
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.
119 =head2 Hash Array References
121 Members of hash arrays are accessed by specifying the hash reference
122 and key separated by the dot 'C<.>' operator.
127 'home' => 'http://www.myserver.com/homepage.html',
129 'this' => 'mypage.html',
130 'next' => 'nextpage.html',
131 'prev' => 'prevpage.html',
137 <a href="[% home %]">Home</a>
138 <a href="[% page.prev %]">Previous Page</a>
139 <a href="[% page.next %]">Next Page</a>
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>
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).
156 message => 'Hello World!',
157 _secret => "On the Internet, no-one knows you're a dog",
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 (..)
173 You can disable this feature by setting the C<$Template::Stash::PRIVATE>
174 package variable to a false value.
176 $Template::Stash::PRIVATE = undef; # now you can thing._private
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>).
182 [% pagename = 'next' %]
183 [% page.$pagename %] # same as [% page.next %]
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
192 [% product.id = 'XYZ-2000'
193 product.desc = 'Bogon Generator'
197 The [% product.id %] [% product.desc %]
198 costs $[% product.price %].00
202 The XYZ-2000 Bogon Generator
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>>.
212 desc = 'Bogon Generator'
220 desc => 'Bogon Generator',
225 =head2 List References
227 Items in lists are also accessed by use of the dot operator.
232 people => [ 'Tom', 'Dick', 'Larry' ],
238 [% people.1 %] # Dick
239 [% people.2 %] # Larry
241 The C<FOREACH> directive can be used to iterate through items in a list.
243 [% FOREACH person IN people %]
253 Lists can be constructed in-situ using the regular anonymous list
254 C<[> ... C<]> construct. Commas between items are optional.
256 [% cols = [ 'red', 'green', 'blue' ] %]
258 [% FOREACH c IN cols %]
264 [% FOREACH c IN [ 'red', 'green', 'blue' ] %]
268 You can also create simple numerical sequences using the C<..> range
271 [% n = [ 1 .. 4 ] %] # n is [ 1, 2, 3, 4 ]
275 z = [x..y] # z is [ 4, 5, 6, 7, 8 ]
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.
287 wizard => sub { return join(' ', 'Abracadabra!', @_) },
292 [% wizard %] # Abracadabra!
293 [% wizard('Hocus Pocus!') %] # Abracadabra! Hocus Pocus!
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
305 # hard coded CGI params for purpose of example
306 cgi => CGI->new('mode=submit&debug=1'),
311 [% FOREACH p IN cgi.param %] # returns list of param keys
312 [% p %] => [% cgi.param(p) %] # fetch each param value
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.
324 [% myobj.method = 10 %]
328 [% myobj.method(10) %]
330 =head2 Passing Parameters and Returning Values
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.
337 mycode => sub { return 'received ' . join(', ', @_) },
343 [% mycode(foo, 20) %] # received 10, 20
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.
355 # look for hash ref as last argument
356 my $params = ref $_[-1] eq 'HASH' ? pop : { };
357 return join($params->{ joint } || ' + ', @_);
362 [% myjoin(10, 20, 30) %]
363 [% myjoin(10, 20, 30, joint = ' - ' %]
364 [% myjoin(joint => ' * ', 10, 20, 30 %]
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.
379 [% r(100, 99, s, t, v) %] # outputs "Romeo"
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.
388 # either is OK, first is recommended
389 items1 => sub { return [ 'foo', 'bar', 'baz' ] },
390 items2 => sub { return ( 'foo', 'bar', 'baz' ) },
395 [% FOREACH i IN items1 %]
399 [% FOREACH i IN items2 %]
403 =head2 Error Handling
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>
413 die "a sick error has occurred\n";
420 [% barf %] # calls sub which throws error via die()
422 [% error.info %] # outputs "a sick error has occurred\n"
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.
430 use Template::Exception;
435 die Template::Exception->new( badpwd => 'password too silly' );
444 Bad password: [% error.info %]
446 Some other '[% error.type %]' error: [% error.info %]
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:
452 die (Template::Exception->new('stop'));
454 has the same effect as the directive:
458 =head1 Virtual Methods
460 The Template Toolkit implements a number of "virtual methods" which
461 can be applied to scalars, hashes or lists. For example:
463 [% mylist = [ 'foo', 'bar', 'baz' ] %]
464 [% newlist = mylist.sort %]
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
471 [% mylist.sort.join(', ') %]
473 Here the C<join> virtual method is called to join the sorted list into
474 a single string, generating the following output:
478 See L<Template::Manual::VMethods> for details of all the virtual
481 =head1 Variable Interpolation
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:
487 [% fullname = "$honorific $firstname $surname" %]
489 Or embedded in plain text when the C<INTERPOLATE> option is set:
491 Dear $honorific $firstname $surname,
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.
499 [% users.$uid %] # same as 'userlist.abw'
501 Curly braces can be used to delimit interpolated variable names where
504 [% users.${me.id}.name %]
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.
509 [% INCLUDE foo/bar.txt %]
511 The above example is equivalent to:
513 [% INCLUDE "foo/bar.txt" %]
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.
518 [% myfile = 'header' %]
519 [% INCLUDE $myfile %]
521 This is equivalent to:
525 Note also that a variable containing a reference to a L<Template::Document>
526 object can also be processed in this way.
529 header => Template::Document->new({ ... }),
534 [% INCLUDE $header %]
536 =head1 Local and Global Variables
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
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.
551 [% BLOCK change_name %]
556 [% INCLUDE change_name %]
558 [% PROCESS change_name %]
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.
570 [% BLOCK all_change %]
571 [% x = 20 %] # changes copy
572 [% y.z = 'zulu' %] # changes original
578 [% INCLUDE all_change %]
580 [% y.z %] # now 'zulu'
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.
586 [% BLOCK new_stuff %]
587 [% # define a new 'y' hash array in local context
593 [% INCLUDE new_stuff %]
594 [% x %] # outputs '10'
595 [% y %] # nothing, y is undefined
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.
601 [% BLOCK new_stuff %]
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.
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.
616 [% global.version = 123 %]
618 =head1 Compile Time Constant Folding
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.
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
630 my $tt = Template->new({
633 release => 'skyrocket',
638 myobj => My::Object->new(),
639 mysub => sub { ... },
644 Within a template, you access these variables using the C<constants>
647 Version [% constants.version %] ([% constants.release %])
648 Background: [% constants.col.back %]
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.
654 You can call subroutines, object methods, and even virtual methods on
657 [% constants.mysub(10, 20) %]
658 [% constants.myobj(30, 40) %]
659 [% constants.col.keys.sort.join(', ') %]
661 One important proviso is that any arguments you pass to subroutines
662 or methods must also be literal values or compile time constants.
664 For example, these are both fine:
667 [% constants.col.keys.sort.join(', ') %]
670 [% constants.col.keys.sort.join(constants.joint) %]
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
676 # ERROR: runtime variable argument!
677 [% constants.col.keys.sort.join(joint) %]
679 The C<CONSTANTS_NAMESPACE> option can be used to provide a different
680 namespace prefix for constant variables. For example:
682 my $tt = Template->new({
687 CONSTANTS_NAMESPACE => 'const',
690 Constants would then be referenced in templates as:
694 =head1 Special Variables
696 A number of special variables are automatically defined by the Template
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.
709 Note that the C<template> variable always references the top-level
710 template, even when processing other template components via C<INCLUDE>,
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.
723 This example should demonstrate the difference:
725 $template->process('foo')
726 || die $template->error(), "\n";
730 [% template.name %] # foo
731 [% component.name %] # foo
736 [% template.name %] # foo
737 [% component.name %] # footer
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.
749 F<outer.tt2> template:
751 [% component.name %] # 'outer.tt2'
752 [% component.caller %] # undef
753 [% component.callers %] # undef
754 [% PROCESS 'middle.tt2' %]
756 F<middle.tt2> template:
758 [% component.name %] # 'middle.tt2'
759 [% component.caller %] # 'outer.tt2'
760 [% component.callers %] # [ 'outer.tt2' ]
761 [% PROCESS 'inner.tt2' %]
763 F<inner.tt2> template:
765 [% component.name %] # 'inner.tt2'
766 [% component.caller %] # 'middle.tt2'
767 [% component.callers %] # [ 'outer.tt2', 'middle.tt2' ]
771 Within a C<FOREACH> loop, the C<loop> variable references the
772 L<Template::Iterator> object responsible for controlling the loop.
774 [% FOREACH item = [ 'foo', 'bar', 'baz' ] -%]
775 [% "Items:\n" IF loop.first -%]
776 [% loop.count %]/[% loop.size %]: [% item %]
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.
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'
800 Be not afeard; the isle is full of noises,
801 Sounds and sweet airs, that give delight and hurt not.
805 <blockquote class="prose">
810 =head1 Compound Variables
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.
818 [% myorg.people.sort('surname').first.fullname %]
820 Intermediate variables may be used and will behave entirely as expected.
822 [% sorted = myorg.people.sort('surname') %]
823 [% sorted.first.fullname %]
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.
834 # perl-indent-level: 4
835 # indent-tabs-mode: nil
838 # vim: expandtab shiftwidth=4: