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 18Template::Manual::Variables - Template variables and code bindings 19 20=head1 Template Variables 21 22A reference to a hash array may be passed as the second argument to the 23L<process()|Template#process()> method, containing definitions of template 24variables. The C<VARIABLES> (a.k.a. C<PRE_DEFINE>) option can also be used to 25pre-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 40F<myfile> template: 41 42 This is version [% version %] ([% release %]). 43 Serial number: [% serial_no %] 44 45Generated Output: 46 47 This is version 3.14 (Sahara) 48 Serial number: 271828 49 50Variable names may contain any alphanumeric characters or underscores. They 51may be lower, upper or mixed case although the usual convention is to use 52lower 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, 54but not recommended due to a possible conflict with an existing or future 55reserved 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 63The variable values may be of virtually any Perl type, including 64simple scalars, references to lists, hash arrays, subroutines or 65objects. The Template Toolkit will automatically apply the correct 66procedure to accessing these values as they are used in the template. 67 68Example 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 82Example 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 96Generated 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 112Regular scalar variables are accessed by simply specifying their name. 113As these are just entries in the top-level variable hash they can be 114considered special cases of hash array referencing as described below, 115with the main namespace hash automatically implied. 116 117 [% article %] 118 119=head2 Hash Array References 120 121Members of hash arrays are accessed by specifying the hash reference 122and key separated by the dot 'C<.>' operator. 123 124Example 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 135Example 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 141Generated 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 147Any key in a hash which starts with a 'C<_>' or 'C<.>' character will be 148considered private and cannot be evaluated or updated from within a 149template. The undefined value will be returned for any such variable 150accessed which the Template Toolkit will silently ignore (unless the 151C<DEBUG> option is enabled). 152 153Example 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 165Example 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 173You can disable this feature by setting the C<$Template::Stash::PRIVATE> 174package variable to a false value. 175 176 $Template::Stash::PRIVATE = undef; # now you can thing._private 177 178To access a hash entry using a key stored in another variable, prefix 179the key variable with 'C<$>' to have it interpolated before use (see 180L<Variable Interpolation>). 181 182 [% pagename = 'next' %] 183 [% page.$pagename %] # same as [% page.next %] 184 185When you assign to a variable that contains multiple namespace 186elements (i.e. it has one or more 'C<.>' characters in the name), 187any hashes required to represent intermediate namespaces will be 188created automatically. In this following example, the C<product> 189variable automatically springs into life as a hash array unless 190otherwise 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 200Generated output: 201 202 The XYZ-2000 Bogon Generator 203 costs $666.00 204 205You can use Perl's familiar C<{> ... C<}> construct to explicitly create 206a hash and assign it to a variable. Note that commas are optional 207between 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 227Items in lists are also accessed by use of the dot operator. 228 229Example data: 230 231 my $vars = { 232 people => [ 'Tom', 'Dick', 'Larry' ], 233 }; 234 235Example template: 236 237 [% people.0 %] # Tom 238 [% people.1 %] # Dick 239 [% people.2 %] # Larry 240 241The 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 247Generated output: 248 249 Hello Tom 250 Hello Dick 251 Hello Larry 252 253Lists can be constructed in-situ using the regular anonymous list 254C<[> ... C<]> construct. Commas between items are optional. 255 256 [% cols = [ 'red', 'green', 'blue' ] %] 257 258 [% FOREACH c IN cols %] 259 [% c %] 260 [% END %] 261 262or: 263 264 [% FOREACH c IN [ 'red', 'green', 'blue' ] %] 265 [% c %] 266 [% END %] 267 268You can also create simple numerical sequences using the C<..> range 269operator: 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 280Template variables can contain references to Perl subroutines. When 281the variable is used, the Template Toolkit will automatically call the 282subroutine, passing any additional arguments specified. The return 283value from the subroutine is used as the variable value and inserted 284into the document output. 285 286 my $vars = { 287 wizard => sub { return join(' ', 'Abracadabra!', @_) }, 288 }; 289 290Example template: 291 292 [% wizard %] # Abracadabra! 293 [% wizard('Hocus Pocus!') %] # Abracadabra! Hocus Pocus! 294 295=head2 Objects 296 297Template variables can also contain references to Perl objects. 298Methods are called using the dot operator to specify the method 299against the object variable. Additional arguments can be specified 300as 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 309Example 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 315Generated output: 316 317 mode => submit 318 debug => 1 319 320Object methods can also be called as lvalues. That is, they can appear on 321the left side of an assignment. The method will be called passing the 322assigning value as an argument. 323 324 [% myobj.method = 10 %] 325 326equivalent to: 327 328 [% myobj.method(10) %] 329 330=head2 Passing Parameters and Returning Values 331 332Subroutines and methods will be passed any arguments specified in the 333template. Any template variables in the argument list will first be 334evaluated and their resultant values passed to the code. 335 336 my $vars = { 337 mycode => sub { return 'received ' . join(', ', @_) }, 338 }; 339 340template: 341 342 [% foo = 10 %] 343 [% mycode(foo, 20) %] # received 10, 20 344 345Named parameters may also be specified. These are automatically collected 346into a single hash array which is passed by reference as the B<last> 347parameter to the sub-routine. Named parameters can be specified using 348either 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 360Example template: 361 362 [% myjoin(10, 20, 30) %] 363 [% myjoin(10, 20, 30, joint = ' - ' %] 364 [% myjoin(joint => ' * ', 10, 20, 30 %] 365 366Generated output: 367 368 10 + 20 + 30 369 10 - 20 - 30 370 10 * 20 * 30 371 372Parenthesised parameters may be added to any element of a variable, 373not just those that are bound to code or object methods. At present, 374parameters will be ignored if the variable isn't "callable" but are 375supported for future extensions. Think of them as "hints" to that 376variable, rather than just arguments passed to a function. 377 378 [% r = 'Romeo' %] 379 [% r(100, 99, s, t, v) %] # outputs "Romeo" 380 381User code should return a value for the variable it represents. This 382can be any of the Perl data types described above: a scalar, or 383reference to a list, hash, subroutine or object. Where code returns a 384list of multiple values the items will automatically be folded into a 385list 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 393Example 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 405Errors can be reported from user code by calling C<die()>. Errors raised 406in this way are caught by the Template Toolkit and converted to 407structured exceptions which can be handled from within the template. 408A reference to the exception object is then available as the C<error> 409variable. 410 411 my $vars = { 412 barf => sub { 413 die "a sick error has occurred\n"; 414 }, 415 }; 416 417Example 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 425Error messages thrown via C<die()> are converted to exceptions of type 426C<undef> (the literal string "undef" rather than the undefined value). 427Exceptions of user-defined types can be thrown by calling C<die()> with 428a 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 439Example 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 449The exception types C<stop> and C<return> are used to implement the 450C<STOP> and C<RETURN> directives. Throwing an exception as: 451 452 die (Template::Exception->new('stop')); 453 454has the same effect as the directive: 455 456 [% STOP %] 457 458=head1 Virtual Methods 459 460The Template Toolkit implements a number of "virtual methods" which 461can be applied to scalars, hashes or lists. For example: 462 463 [% mylist = [ 'foo', 'bar', 'baz' ] %] 464 [% newlist = mylist.sort %] 465 466Here C<mylist> is a regular reference to a list, and 'sort' is 467a virtual method that returns a new list of the items in sorted 468order. You can chain multiple virtual methods together. For 469example: 470 471 [% mylist.sort.join(', ') %] 472 473Here the C<join> virtual method is called to join the sorted list into 474a single string, generating the following output: 475 476 bar, baz, foo 477 478See L<Template::Manual::VMethods> for details of all the virtual 479methods available. 480 481=head1 Variable Interpolation 482 483The Template Toolkit uses C<$> consistently to indicate that a variable 484should be interpolated in position. Most frequently, you see this in 485double-quoted strings: 486 487 [% fullname = "$honorific $firstname $surname" %] 488 489Or embedded in plain text when the C<INTERPOLATE> option is set: 490 491 Dear $honorific $firstname $surname, 492 493The same rules apply within directives. If a variable is prefixed 494with a C<$> then it is replaced with its value before being used. The 495most common use is to retrieve an element from a hash where the key is 496stored in a variable. 497 498 [% uid = 'abw' %] 499 [% users.$uid %] # same as 'userlist.abw' 500 501Curly braces can be used to delimit interpolated variable names where 502necessary. 503 504 [% users.${me.id}.name %] 505 506Directives such as C<INCLUDE>, C<PROCESS>, etc., that accept a template name 507as the first argument, will automatically quote it for convenience. 508 509 [% INCLUDE foo/bar.txt %] 510 511The above example is equivalent to: 512 513 [% INCLUDE "foo/bar.txt" %] 514 515To C<INCLUDE> a template whose name is stored in a variable, simply 516prefix the variable name with C<$> to have it interpolated. 517 518 [% myfile = 'header' %] 519 [% INCLUDE $myfile %] 520 521This is equivalent to: 522 523 [% INCLUDE header %] 524 525Note also that a variable containing a reference to a L<Template::Document> 526object can also be processed in this way. 527 528 my $vars = { 529 header => Template::Document->new({ ... }), 530 }; 531 532Example template: 533 534 [% INCLUDE $header %] 535 536=head1 Local and Global Variables 537 538Any simple variables that you create, or any changes you make to 539existing variables, will only persist while the template is being 540processed. The top-level variable hash is copied before processing 541begins and any changes to variables are made in this copy, leaving the 542original intact. 543 544The same thing happens when you C<INCLUDE> another template. The current 545namespace hash is cloned to prevent any variable changes made in the included 546template from interfering with existing variables. The C<PROCESS> option bypasses 547the localisation step altogether making it slightly faster, but requiring 548greater attention to the possibility of side effects caused by creating or 549changing 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 561Dotted compound variables behave slightly differently because the 562localisation process is only skin deep. The current variable 563namespace hash is copied, but no attempt is made to perform a 564deep-copy of other structures within it (hashes, arrays, objects, 565etc). A variable referencing a hash, for example, will be copied to 566create a new reference but which points to the same hash. Thus, the 567general rule is that simple variables (undotted variables) are 568localised, 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 582If you create a complex structure such as a hash or list reference 583within a local template context then it will cease to exist when 584the 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 597Similarly, if you update an element of a compound variable which 598I<doesn't> already exists then a hash will be created automatically 599and deleted again at the end of the block. 600 601 [% BLOCK new_stuff %] 602 [% y.z = 'zulu' %] 603 [% END %] 604 605However, if the hash I<does> already exist then you will modify the 606original with permanent effect. To avoid potential confusion, it is 607recommended that you don't update elements of complex variables from 608within blocks or templates included by another. 609 610If you want to create or update truly global variables then you can 611use the 'global' namespace. This is a hash array automatically created 612in the top-level namespace which all templates, localised or otherwise 613see the same reference to. Changes made to variables within this 614hash are visible across all templates. 615 616 [% global.version = 123 %] 617 618=head1 Compile Time Constant Folding 619 620In addition to variables that get resolved each time a template is 621processed, you can also define variables that get resolved just once 622when the template is compiled. This generally results in templates 623processing faster because there is less work to be done. 624 625To define compile-time constants, specify a C<CONSTANTS> hash as a 626constructor item as per C<VARIABLES>. The C<CONSTANTS> hash can contain any 627kind of complex, nested, or dynamic data structures, just like regular 628variables. 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 644Within a template, you access these variables using the C<constants> 645namespace prefix. 646 647 Version [% constants.version %] ([% constants.release %]) 648 Background: [% constants.col.back %] 649 650When the template is compiled, these variable references are replaced 651with the corresponding value. No further variable lookup is then 652required when the template is processed. 653 654You can call subroutines, object methods, and even virtual methods on 655constant variables. 656 657 [% constants.mysub(10, 20) %] 658 [% constants.myobj(30, 40) %] 659 [% constants.col.keys.sort.join(', ') %] 660 661One important proviso is that any arguments you pass to subroutines 662or methods must also be literal values or compile time constants. 663 664For 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 672But this next example will raise an error at parse time because 673C<joint> is a runtime variable and cannot be determined at compile 674time. 675 676 # ERROR: runtime variable argument! 677 [% constants.col.keys.sort.join(joint) %] 678 679The C<CONSTANTS_NAMESPACE> option can be used to provide a different 680namespace 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 690Constants would then be referenced in templates as: 691 692 [% const.version %] 693 694=head1 Special Variables 695 696A number of special variables are automatically defined by the Template 697Toolkit. 698 699=head2 template 700 701The C<template> variable contains a reference to the main template being 702processed, in the form of a L<Template::Document> object. This variable is 703correctly defined within C<PRE_PROCESS>, C<PROCESS> and C<POST_PROCESS> 704templates, allowing standard headers, footers, etc., to access metadata items 705from the main template. The C<name> and C<modtime> metadata items are 706automatically provided, giving the template name and modification time in 707seconds since the epoch. 708 709Note that the C<template> variable always references the top-level 710template, even when processing other template components via C<INCLUDE>, 711C<PROCESS>, etc. 712 713=head2 component 714 715The C<component> variable is like C<template> but always contains a 716reference to the current, innermost template component being processed. 717In the main template, the C<template> and C<component> variable will 718reference the same L<Template::Document> object. In any other template 719component called from the main template, the C<template> variable 720will remain unchanged, but C<component> will contain a new reference 721to the current component. 722 723This example should demonstrate the difference: 724 725 $template->process('foo') 726 || die $template->error(), "\n"; 727 728F<foo> template: 729 730 [% template.name %] # foo 731 [% component.name %] # foo 732 [% PROCESS footer %] 733 734F<footer> template: 735 736 [% template.name %] # foo 737 [% component.name %] # footer 738 739Additionally, the C<component> variable has two special fields: 740C<caller> and C<callers>. C<caller> contains the name of the template 741that called the current template (or undef if the values of C<template> 742and C<component> are the same). C<callers> contains a reference to a 743list of all the templates that have been called on the road to calling 744the current component template (like a call stack), with the 745outer-most template first. 746 747Here's an example: 748 749F<outer.tt2> template: 750 751 [% component.name %] # 'outer.tt2' 752 [% component.caller %] # undef 753 [% component.callers %] # undef 754 [% PROCESS 'middle.tt2' %] 755 756F<middle.tt2> template: 757 758 [% component.name %] # 'middle.tt2' 759 [% component.caller %] # 'outer.tt2' 760 [% component.callers %] # [ 'outer.tt2' ] 761 [% PROCESS 'inner.tt2' %] 762 763F<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 771Within a C<FOREACH> loop, the C<loop> variable references the 772L<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 781Within a C<CATCH> block, the C<error> variable contains a reference to the 782L<Template::Exception> object thrown from within the C<TRY> block. The 783C<type> and C<info> methods can be called or the variable itself can 784be 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 795The C<WRAPPER> method captures the output from a template block and then 796includes a named template, passing the captured output as the 'content' 797variable. 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 812Compound 'dotted' variables may contain any number of separate 813elements. Each element may evaluate to any of the permitted variable 814types and the processor will then correctly use this value to evaluate 815the rest of the variable. Arguments may be passed to any of the 816intermediate elements. 817 818 [% myorg.people.sort('surname').first.fullname %] 819 820Intermediate variables may be used and will behave entirely as expected. 821 822 [% sorted = myorg.people.sort('surname') %] 823 [% sorted.first.fullname %] 824 825This simplified dotted notation has the benefit of hiding the 826implementation details of your data. For example, you could implement 827a data structure as a hash array one day and then change it to an 828object 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: 839