1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN">
<html>
<head>
<title>Template::Manual::Variables</title>
<link rel="stylesheet" type="text/css" href="../css/blue.css" title="Clear Blue">
<link rel="alternate stylesheet" type="text/css" href="../css/orange.css" title="Clear Orange">
<link rel="alternate stylesheet" type="text/css" href="../css/green.css" title="Clear Green">
<link rel="alternate stylesheet" type="text/css" href="../css/purple.css" title="Clear Purple">
<link rel="alternate stylesheet" type="text/css" href="../css/grey.css" title="Clear Grey">
<link rel="alternate stylesheet" type="text/css" href="../css/print.css" title="Print">
<!--[if IE 6]>
<link rel="stylesheet" type="text/css" href="../css/ie6.css" />
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="../css/ie7.css" />
<![endif]-->
<link rel="stylesheet" type="text/css" href="../css/print.css" media="print">
<script type="text/javascript" src="../js/tt2.js"></script>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta name="author" content="Andy Wardley">
</head>
<body id="body">
<div id="layout">
<div id="header">
<a href="../index.html" id="logo" alt="" title="Click for the Home Page"><span class="alt">TT2 Home Page</span></a>
<ul id="trail">
<li><a href="../manual/index.html">Manual</a></li>
<li class="last"><a href="../manual/Variables.html">Variables</a></li>
</ul>
<div class="controls">
<a href="#" class="menu show" onclick="widescreen_off(); return false" title="Show Menu">
<span class="about">Click to view the menu. It's very nice.</span>
</a>
<a href="#" class="menu hide" onclick="widescreen_on(); return false" title="Hide Menu">
<span class="about">Click to hide the menu and go all widescreen!</span>
</a>
<div class="pager">
<a href="../manual/Directives.html" title="Template::Manual::Directives" class="go back">Back<span class="about"><h4>Template::Manual::Directives</h4>Template directives</span></a>
<a href="../manual/index.html" title="Template::Manual" class="go up">Up<span class="about"><h4>Template::Manual</h4>Template Toolkit User Manual</span></a>
<a href="../manual/VMethods.html" title="Template::Manual::VMethods" class="go next">Next<span class="about"><h4>Template::Manual::VMethods</h4>Virtual Methods</span></a>
</div>
</div>
<h1 class="headline">Template::Manual::Variables</h1>
<h2 class="subhead">Template variables and code bindings</h1>
</div>
<div id="page">
<div id="sidebar">
<a href="../index.html" id="logo"></a>
<div id="menu">
<ul class="menu">
<li class="l0 first"><a href="../manual/index.html" class="warm">Manual</a></li>
<li class="l1"><a href="../manual/Intro.html">Intro</a></li>
<li class="l1"><a href="../manual/Syntax.html">Syntax</a></li>
<li class="l1"><a href="../manual/Directives.html">Directives</a></li>
<li class="l1"><a href="../manual/Variables.html" class="warm">Variables</a></li>
<li class="l1"><a href="../manual/VMethods.html">VMethods</a></li>
<li class="l1"><a href="../manual/Config.html">Config</a></li>
<li class="l1"><a href="../manual/Filters.html">Filters</a></li>
<li class="l1"><a href="../manual/Plugins.html">Plugins</a></li>
<li class="l1"><a href="../manual/Internals.html">Internals</a></li>
<li class="l1"><a href="../manual/Views.html">Views</a></li>
<li class="l1"><a href="../manual/Credits.html">Credits</a></li>
<li class="l0"><a href="../modules/index.html">Modules</a></li>
<li class="l0"><a href="../tools/index.html">Tools</a></li>
<li class="l0"><a href="../tutorial/index.html">Tutorial</a></li>
<li class="l0 last"><a href="../faq/index.html">FAQ</a></li>
</ul>
<div class="foot"></div>
</div>
</div>
<div id="content">
<div class="section">
<div class="head">
<h1 id="contents" onclick="switch_section(this)" title="Click title to show/hide section content.">Contents</h1>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<ul class="toc">
<li class=""><a href="#Template_Variables">Template Variables</a></li>
<li class="sub"><a href="#section_Scalar_Values">Scalar Values</a></li>
<li class="sub"><a href="#section_Hash_Array_References">Hash Array References</a></li>
<li class="sub"><a href="#section_List_References">List References</a></li>
<li class="sub"><a href="#section_Subroutines">Subroutines</a></li>
<li class="sub"><a href="#section_Objects">Objects</a></li>
<li class="sub"><a href="#section_Passing_Parameters_and_Returning_Values">Passing Parameters and Returning Values</a></li>
<li class="sub"><a href="#section_Error_Handling">Error Handling</a></li>
<li class=""><a href="#Virtual_Methods">Virtual Methods</a></li>
<li class=""><a href="#Variable_Interpolation">Variable Interpolation</a></li>
<li class=""><a href="#Local_and_Global_Variables">Local and Global Variables</a></li>
<li class=""><a href="#Compile_Time_Constant_Folding">Compile Time Constant Folding</a></li>
<li class=""><a href="#Special_Variables">Special Variables</a></li>
<li class="sub"><a href="#section_template">template</a></li>
<li class="sub"><a href="#section_component">component</a></li>
<li class="sub"><a href="#section_loop">loop</a></li>
<li class="sub"><a href="#section_error">error</a></li>
<li class="sub"><a href="#section_content">content</a></li>
<li class=""><a href="#Compound_Variables">Compound Variables</a></li>
</ul>
</div>
</div>
<div class="pod">
<div class="section">
<div class="head">
<h1 id="Template_Variables" onclick="switch_section(this)" title="Click title to show/hide section content.">Template Variables</h1>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
A reference to a hash array may be passed as the second argument to the
<a href="../modules/Template.html#method_process">process()</a>
method, containing definitions of template variables. The
<code>VARIABLES</code> (a.k.a. <code>PRE_DEFINE</code>) option can also
be used to pre-define variables for all templates processed by the
object.
</p>
<pre>my $tt = Template->new({
VARIABLES => {
version => 3.14,
release => 'Sahara',
},
});
my $vars = {
serial_no => 271828,
};
$tt->process('myfile', $vars);</pre>
<p>
<i>myfile</i> template:
</p>
<pre>This is version <span class="tt">[% version %]</span> (<span class="tt">[% release %]</span>).
Serial number: <span class="tt">[% serial_no %]</span></pre>
<p>
Generated Output:
</p>
<pre>This is version 3.14 (Sahara)
Serial number: 271828</pre>
<p>
Variable names may contain any alphanumeric characters or underscores.
They may be lower, upper or mixed case although the usual convention is
to use lower case. The case <i>is</i> significant however, and
'<code>foo</code>', '<code>Foo</code>' and '<code>FOO</code>' are all
different variables. Upper case variable names are permitted, but not
recommended due to a possible conflict with an existing or future
reserved word. As of version 2.00, these are:
</p>
<pre>GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER
IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP
CLEAR TO STEP AND OR NOT MOD DIV END</pre>
<p>
The variable values may be of virtually any Perl type, including simple
scalars, references to lists, hash arrays, subroutines or objects. The
Template Toolkit will automatically apply the correct procedure to
accessing these values as they are used in the template.
</p>
<p>
Example data:
</p>
<pre>my $vars = {
article => 'The Third Shoe',
person => {
id => 314,
name => 'Mr. Blue',
email => 'blue@nowhere.org',
},
primes => [ 2, 3, 5, 7, 11, 13 ],
wizard => sub { return join(' ', 'Abracadabra!', @_) },
cgi => CGI->new('mode=submit&debug=1'),
};</pre>
<p>
Example template:
</p>
<pre><span class="tt">[% article %]</span>
<span class="tt">[% person.id %]</span>: <span class="tt">[% person.name %]</span> <<span class="tt">[% person.email %]</span>>
<span class="tt">[% primes.first %]</span> - <span class="tt">[% primes.last %]</span>, including <span class="tt">[% primes.3 %]</span>
<span class="tt">[% primes.size %]</span> prime numbers: <span class="tt">[% primes.join(', ') %]</span>
<span class="tt">[% wizard %]</span>
<span class="tt">[% wizard('Hocus Pocus!') %]</span>
<span class="tt">[% cgi.param('mode') %]</span></pre>
<p>
Generated output:
</p>
<pre>The Third Shoe
314: Mr. Blue <blue@nowhere.org>
2 - 13, including 7
6 prime numbers: 2, 3, 5, 7, 11, 13
Abracadabra!
Abracadabra! Hocus Pocus!
submit</pre>
<div class="subsection">
<div class="head">
<h2 id="section_Scalar_Values" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Scalar Values</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
Regular scalar variables are accessed by simply specifying their name. As
these are just entries in the top-level variable hash they can be
considered special cases of hash array referencing as described below,
with the main namespace hash automatically implied.
</p>
<pre><span class="tt">[% article %]</span></pre>
</div>
</div> <div class="subsection">
<div class="head">
<h2 id="section_Hash_Array_References" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Hash Array References</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
Members of hash arrays are accessed by specifying the hash reference and
key separated by the dot '<code>.</code>' operator.
</p>
<p>
Example data:
</p>
<pre>my $vars = {
'home' => 'http://www.myserver.com/homepage.html',
'page' => {
'this' => 'mypage.html',
'next' => 'nextpage.html',
'prev' => 'prevpage.html',
},
};</pre>
<p>
Example template:
</p>
<pre><a href="<span class="tt">[% home %]</span>">Home</a>
<a href="<span class="tt">[% page.prev %]</span>">Previous Page</a>
<a href="<span class="tt">[% page.next %]</span>">Next Page</a></pre>
<p>
Generated output:
</p>
<pre><a href="http://www.myserver.com/homepage.html">Home</a>
<a href="prevpage.html">Previous Page</a>
<a href="nextpage.html">Next Page</a></pre>
<p>
Any key in a hash which starts with a '<code>_</code>' or
'<code>.</code>' character will be considered private and cannot be
evaluated or updated from within a template. The undefined value will be
returned for any such variable accessed which the Template Toolkit will
silently ignore (unless the <code>DEBUG</code> option is enabled).
</p>
<p>
Example data:
</p>
<pre>my $vars = {
message => 'Hello World!',
_secret => "On the Internet, no-one knows you're a dog",
thing => {
public => 123,
_private => 456,
'.hidden' => 789,
},
};</pre>
<p>
Example template:
</p>
<pre><span class="tt">[% message %]</span> # outputs "Hello World!"
<span class="tt">[% _secret %]</span> # no output
<span class="tt">[% thing.public %]</span> # outputs "123"
<span class="tt">[% thing._private %]</span> # no output
<span class="tt">[% thing..hidden %]</span> # ERROR: unexpected token (..)</pre>
<p>
You can disable this feature by setting the
<code>$Template::Stash::PRIVATE</code> package variable to a false value.
</p>
<pre>$Template::Stash::PRIVATE = undef; # now you can thing._private</pre>
<p>
To access a hash entry using a key stored in another variable, prefix the
key variable with '<code>$</code>' to have it interpolated before use
(see <a href="#Variable_Interpolation">Variable Interpolation</a>).
</p>
<pre><span class="tt">[% pagename = 'next' %]</span>
<span class="tt">[% page.$pagename %]</span> # same as <span class="tt">[% page.next %]</span></pre>
<p>
When you assign to a variable that contains multiple namespace elements
(i.e. it has one or more '<code>.</code>' characters in the name), any
hashes required to represent intermediate namespaces will be created
automatically. In this following example, the <code>product</code>
variable automatically springs into life as a hash array unless otherwise
defined.
</p>
<pre><span class="tt">[% product.id = 'XYZ-2000'
product.desc = 'Bogon Generator'
product.price = 666
%]</span>
The <span class="tt">[% product.id %]</span> <span class="tt">[% product.desc %]</span>
costs $<span class="tt">[% product.price %]</span>.00</pre>
<p>
Generated output:
</p>
<pre>The XYZ-2000 Bogon Generator
costs $666.00</pre>
<p>
You can use Perl's familiar <code>{</code> ... <code>}</code> construct
to explicitly create a hash and assign it to a variable. Note that commas
are optional between key/value pairs and <code>=</code> can be used in
place of <code>=></code>.
</p>
<pre># minimal TT style
<span class="tt">[% product = {
id = 'XYZ-2000'
desc = 'Bogon Generator'
price = 666
}
%]</span>
# perl style
<span class="tt">[% product = {
id => 'XYZ-2000',
desc => 'Bogon Generator',
price => 666,
}
%]</span></pre>
</div>
</div> <div class="subsection">
<div class="head">
<h2 id="section_List_References" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">List References</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
Items in lists are also accessed by use of the dot operator.
</p>
<p>
Example data:
</p>
<pre>my $vars = {
people => [ 'Tom', 'Dick', 'Larry' ],
};</pre>
<p>
Example template:
</p>
<pre><span class="tt">[% people.0 %]</span> # Tom
<span class="tt">[% people.1 %]</span> # Dick
<span class="tt">[% people.2 %]</span> # Larry</pre>
<p>
The <code>FOREACH</code> directive can be used to iterate through items
in a list.
</p>
<pre><span class="tt">[% FOREACH person IN people %]</span>
Hello <span class="tt">[% person %]</span>
<span class="tt">[% END %]</span></pre>
<p>
Generated output:
</p>
<pre>Hello Tom
Hello Dick
Hello Larry</pre>
<p>
Lists can be constructed in-situ using the regular anonymous list
<code>[</code> ... <code>]</code> construct. Commas between items are
optional.
</p>
<pre><span class="tt">[% cols = [ 'red', 'green', 'blue' ] %]</span>
<span class="tt">[% FOREACH c IN cols %]</span>
<span class="tt">[% c %]</span>
<span class="tt">[% END %]</span></pre>
<p>
or:
</p>
<pre><span class="tt">[% FOREACH c IN [ 'red', 'green', 'blue' ] %]</span>
<span class="tt">[% c %]</span>
<span class="tt">[% END %]</span></pre>
<p>
You can also create simple numerical sequences using the <code>..</code>
range operator:
</p>
<pre><span class="tt">[% n = [ 1 .. 4 ] %]</span> # n is [ 1, 2, 3, 4 ]
<span class="tt">[% x = 4
y = 8
z = [x..y] # z is [ 4, 5, 6, 7, 8 ]
%]</span></pre>
</div>
</div> <div class="subsection">
<div class="head">
<h2 id="section_Subroutines" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Subroutines</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
Template variables can contain references to Perl subroutines. When the
variable is used, the Template Toolkit will automatically call the
subroutine, passing any additional arguments specified. The return value
from the subroutine is used as the variable value and inserted into the
document output.
</p>
<pre>my $vars = {
wizard => sub { return join(' ', 'Abracadabra!', @_) },
};</pre>
<p>
Example template:
</p>
<pre><span class="tt">[% wizard %]</span> # Abracadabra!
<span class="tt">[% wizard('Hocus Pocus!') %]</span> # Abracadabra! Hocus Pocus!</pre>
</div>
</div> <div class="subsection">
<div class="head">
<h2 id="section_Objects" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Objects</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
Template variables can also contain references to Perl objects. Methods
are called using the dot operator to specify the method against the
object variable. Additional arguments can be specified as with
subroutines.
</p>
<pre>use CGI;
my $vars = {
# hard coded CGI params for purpose of example
cgi => CGI->new('mode=submit&debug=1'),
};</pre>
<p>
Example template:
</p>
<pre><span class="tt">[% FOREACH p IN cgi.param %]</span> # returns list of param keys
<span class="tt">[% p %]</span> => <span class="tt">[% cgi.param(p) %]</span> # fetch each param value
<span class="tt">[% END %]</span></pre>
<p>
Generated output:
</p>
<pre>mode => submit
debug => 1</pre>
<p>
Object methods can also be called as lvalues. That is, they can appear on
the left side of an assignment. The method will be called passing the
assigning value as an argument.
</p>
<pre><span class="tt">[% myobj.method = 10 %]</span></pre>
<p>
equivalent to:
</p>
<pre><span class="tt">[% myobj.method(10) %]</span></pre>
</div>
</div> <div class="subsection">
<div class="head">
<h2 id="section_Passing_Parameters_and_Returning_Values" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Passing Parameters and Returning Values</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
Subroutines and methods will be passed any arguments specified in the
template. Any template variables in the argument list will first be
evaluated and their resultant values passed to the code.
</p>
<pre>my $vars = {
mycode => sub { return 'received ' . join(', ', @_) },
};</pre>
<p>
template:
</p>
<pre><span class="tt">[% foo = 10 %]</span>
<span class="tt">[% mycode(foo, 20) %]</span> # received 10, 20</pre>
<p>
Named parameters may also be specified. These are automatically collected
into a single hash array which is passed by reference as the <b>last</b>
parameter to the sub-routine. Named parameters can be specified using
either <code>=></code> or <code>=</code> and can appear anywhere in
the argument list.
</p>
<pre>my $vars = {
myjoin => \&myjoin,
};
sub myjoin {
# look for hash ref as last argument
my $params = ref $_[-1] eq 'HASH' ? pop : { };
return join($params->{ joint } || ' + ', @_);
}</pre>
<p>
Example template:
</p>
<pre><span class="tt">[% myjoin(10, 20, 30) %]</span>
<span class="tt">[% myjoin(10, 20, 30, joint = ' - ' %]</span>
<span class="tt">[% myjoin(joint => ' * ', 10, 20, 30 %]</span></pre>
<p>
Generated output:
</p>
<pre>10 + 20 + 30
10 - 20 - 30
10 * 20 * 30</pre>
<p>
Parenthesised parameters may be added to any element of a variable, not
just those that are bound to code or object methods. At present,
parameters will be ignored if the variable isn't "callable" but are
supported for future extensions. Think of them as "hints" to that
variable, rather than just arguments passed to a function.
</p>
<pre><span class="tt">[% r = 'Romeo' %]</span>
<span class="tt">[% r(100, 99, s, t, v) %]</span> # outputs "Romeo"</pre>
<p>
User code should return a value for the variable it represents. This can
be any of the Perl data types described above: a scalar, or reference to
a list, hash, subroutine or object. Where code returns a list of multiple
values the items will automatically be folded into a list reference which
can be accessed as per normal.
</p>
<pre>my $vars = {
# either is OK, first is recommended
items1 => sub { return [ 'foo', 'bar', 'baz' ] },
items2 => sub { return ( 'foo', 'bar', 'baz' ) },
};</pre>
<p>
Example template:
</p>
<pre><span class="tt">[% FOREACH i IN items1 %]</span>
...
<span class="tt">[% END %]</span>
<span class="tt">[% FOREACH i IN items2 %]</span>
...
<span class="tt">[% END %]</span></pre>
</div>
</div> <div class="subsection">
<div class="head">
<h2 id="section_Error_Handling" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">Error Handling</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
Errors can be reported from user code by calling <code>die()</code>.
Errors raised in this way are caught by the Template Toolkit and
converted to structured exceptions which can be handled from within the
template. A reference to the exception object is then available as the
<code>error</code> variable.
</p>
<pre>my $vars = {
barf => sub {
die "a sick error has occurred\n";
},
};</pre>
<p>
Example template:
</p>
<pre><span class="tt">[% TRY %]</span>
<span class="tt">[% barf %]</span> # calls sub which throws error via die()
<span class="tt">[% CATCH %]</span>
<span class="tt">[% error.info %]</span> # outputs "a sick error has occurred\n"
<span class="tt">[% END %]</span></pre>
<p>
Error messages thrown via <code>die()</code> are converted to exceptions
of type <code>undef</code> (the literal string "undef" rather than the
undefined value). Exceptions of user-defined types can be thrown by
calling <code>die()</code> with a reference to a <a href="../modules/Template/Exception.html">Template::Exception</a> object.
</p>
<pre>use Template::Exception;
my $vars = {
login => sub {
...do something...
die Template::Exception->new( badpwd => 'password too silly' );
},
};</pre>
<p>
Example template:
</p>
<pre><span class="tt">[% TRY %]</span>
<span class="tt">[% login %]</span>
<span class="tt">[% CATCH badpwd %]</span>
Bad password: <span class="tt">[% error.info %]</span>
<span class="tt">[% CATCH %]</span>
Some other '<span class="tt">[% error.type %]</span>' error: <span class="tt">[% error.info %]</span>
<span class="tt">[% END %]</span></pre>
<p>
The exception types <code>stop</code> and <code>return</code> are used to
implement the <code>STOP</code> and <code>RETURN</code> directives.
Throwing an exception as:
</p>
<pre>die (Template::Exception->new('stop'));</pre>
<p>
has the same effect as the directive:
</p>
<pre><span class="tt">[% STOP %]</span></pre>
</div>
</div>
</div>
</div>
<div class="section">
<div class="head">
<h1 id="Virtual_Methods" onclick="switch_section(this)" title="Click title to show/hide section content.">Virtual Methods</h1>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
The Template Toolkit implements a number of "virtual methods" which can
be applied to scalars, hashes or lists. For example:
</p>
<pre><span class="tt">[% mylist = [ 'foo', 'bar', 'baz' ] %]</span>
<span class="tt">[% newlist = mylist.sort %]</span></pre>
<p>
Here <code>mylist</code> is a regular reference to a list, and 'sort' is
a virtual method that returns a new list of the items in sorted order.
You can chain multiple virtual methods together. For example:
</p>
<pre><span class="tt">[% mylist.sort.join(', ') %]</span></pre>
<p>
Here the <code>join</code> virtual method is called to join the sorted
list into a single string, generating the following output:
</p>
<pre>bar, baz, foo</pre>
<p>
See <a href="../manual/VMethods.html">Template::Manual::VMethods</a> for details of all the virtual
methods available.
</p>
</div>
</div>
<div class="section">
<div class="head">
<h1 id="Variable_Interpolation" onclick="switch_section(this)" title="Click title to show/hide section content.">Variable Interpolation</h1>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
The Template Toolkit uses <code>$</code> consistently to indicate that a
variable should be interpolated in position. Most frequently, you see
this in double-quoted strings:
</p>
<pre><span class="tt">[% fullname = "$honorific $firstname $surname" %]</span></pre>
<p>
Or embedded in plain text when the <code>INTERPOLATE</code> option is
set:
</p>
<pre>Dear $honorific $firstname $surname,</pre>
<p>
The same rules apply within directives. If a variable is prefixed with a
<code>$</code> then it is replaced with its value before being used. The
most common use is to retrieve an element from a hash where the key is
stored in a variable.
</p>
<pre><span class="tt">[% uid = 'abw' %]</span>
<span class="tt">[% users.$uid %]</span> # same as 'userlist.abw'</pre>
<p>
Curly braces can be used to delimit interpolated variable names where
necessary.
</p>
<pre><span class="tt">[% users.${me.id}.name %]</span></pre>
<p>
Directives such as <code>INCLUDE</code>, <code>PROCESS</code>, etc., that
accept a template name as the first argument, will automatically quote it
for convenience.
</p>
<pre><span class="tt">[% INCLUDE foo/bar.txt %]</span></pre>
<p>
The above example is equivalent to:
</p>
<pre><span class="tt">[% INCLUDE "foo/bar.txt" %]</span></pre>
<p>
To <code>INCLUDE</code> a template whose name is stored in a variable,
simply prefix the variable name with <code>$</code> to have it
interpolated.
</p>
<pre><span class="tt">[% myfile = 'header' %]</span>
<span class="tt">[% INCLUDE $myfile %]</span></pre>
<p>
This is equivalent to:
</p>
<pre><span class="tt">[% INCLUDE header %]</span></pre>
<p>
Note also that a variable containing a reference to a <a href="../modules/Template/Document.html">Template::Document</a> object can
also be processed in this way.
</p>
<pre>my $vars = {
header => Template::Document->new({ ... }),
};</pre>
<p>
Example template:
</p>
<pre><span class="tt">[% INCLUDE $header %]</span></pre>
</div>
</div>
<div class="section">
<div class="head">
<h1 id="Local_and_Global_Variables" onclick="switch_section(this)" title="Click title to show/hide section content.">Local and Global Variables</h1>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
Any simple variables that you create, or any changes you make to existing
variables, will only persist while the template is being processed. The
top-level variable hash is copied before processing begins and any
changes to variables are made in this copy, leaving the original intact.
</p>
<p>
The same thing happens when you <code>INCLUDE</code> another template.
The current namespace hash is cloned to prevent any variable changes made
in the included template from interfering with existing variables. The
<code>PROCESS</code> option bypasses the localisation step altogether
making it slightly faster, but requiring greater attention to the
possibility of side effects caused by creating or changing any variables
within the processed template.
</p>
<pre><span class="tt">[% BLOCK change_name %]</span>
<span class="tt">[% name = 'bar' %]</span>
<span class="tt">[% END %]</span>
<span class="tt">[% name = 'foo' %]</span>
<span class="tt">[% INCLUDE change_name %]</span>
<span class="tt">[% name %]</span> # foo
<span class="tt">[% PROCESS change_name %]</span>
<span class="tt">[% name %]</span> # bar</pre>
<p>
Dotted compound variables behave slightly differently because the
localisation process is only skin deep. The current variable namespace
hash is copied, but no attempt is made to perform a deep-copy of other
structures within it (hashes, arrays, objects, etc). A variable
referencing a hash, for example, will be copied to create a new reference
but which points to the same hash. Thus, the general rule is that simple
variables (undotted variables) are localised, but existing complex
structures (dotted variables) are not.
</p>
<pre><span class="tt">[% BLOCK all_change %]</span>
<span class="tt">[% x = 20 %]</span> # changes copy
<span class="tt">[% y.z = 'zulu' %]</span> # changes original
<span class="tt">[% END %]</span>
<span class="tt">[% x = 10
y = { z => 'zebra' }
%]</span>
<span class="tt">[% INCLUDE all_change %]</span>
<span class="tt">[% x %]</span> # still '10'
<span class="tt">[% y.z %]</span> # now 'zulu'</pre>
<p>
If you create a complex structure such as a hash or list reference within
a local template context then it will cease to exist when the template is
finished processing.
</p>
<pre><span class="tt">[% BLOCK new_stuff %]</span>
<span class="tt">[% # define a new 'y' hash array in local context
y = { z => 'zulu' }
%]</span>
<span class="tt">[% END %]</span>
<span class="tt">[% x = 10 %]</span>
<span class="tt">[% INCLUDE new_stuff %]</span>
<span class="tt">[% x %]</span> # outputs '10'
<span class="tt">[% y %]</span> # nothing, y is undefined</pre>
<p>
Similarly, if you update an element of a compound variable which
<i>doesn't</i> already exists then a hash will be created automatically
and deleted again at the end of the block.
</p>
<pre><span class="tt">[% BLOCK new_stuff %]</span>
<span class="tt">[% y.z = 'zulu' %]</span>
<span class="tt">[% END %]</span></pre>
<p>
However, if the hash <i>does</i> already exist then you will modify the
original with permanent effect. To avoid potential confusion, it is
recommended that you don't update elements of complex variables from
within blocks or templates included by another.
</p>
<p>
If you want to create or update truly global variables then you can use
the 'global' namespace. This is a hash array automatically created in the
top-level namespace which all templates, localised or otherwise see the
same reference to. Changes made to variables within this hash are visible
across all templates.
</p>
<pre><span class="tt">[% global.version = 123 %]</span></pre>
</div>
</div>
<div class="section">
<div class="head">
<h1 id="Compile_Time_Constant_Folding" onclick="switch_section(this)" title="Click title to show/hide section content.">Compile Time Constant Folding</h1>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
In addition to variables that get resolved each time a template is
processed, you can also define variables that get resolved just once when
the template is compiled. This generally results in templates processing
faster because there is less work to be done.
</p>
<p>
To define compile-time constants, specify a <code>CONSTANTS</code> hash
as a constructor item as per <code>VARIABLES</code>. The
<code>CONSTANTS</code> hash can contain any kind of complex, nested, or
dynamic data structures, just like regular variables.
</p>
<pre>my $tt = Template->new({
CONSTANTS => {
version => 3.14,
release => 'skyrocket',
col => {
back => '#ffffff',
fore => '#000000',
},
myobj => My::Object->new(),
mysub => sub { ... },
joint => ', ',
},
});</pre>
<p>
Within a template, you access these variables using the
<code>constants</code> namespace prefix.
</p>
<pre>Version <span class="tt">[% constants.version %]</span> (<span class="tt">[% constants.release %]</span>)
Background: <span class="tt">[% constants.col.back %]</span></pre>
<p>
When the template is compiled, these variable references are replaced
with the corresponding value. No further variable lookup is then required
when the template is processed.
</p>
<p>
You can call subroutines, object methods, and even virtual methods on
constant variables.
</p>
<pre><span class="tt">[% constants.mysub(10, 20) %]</span>
<span class="tt">[% constants.myobj(30, 40) %]</span>
<span class="tt">[% constants.col.keys.sort.join(', ') %]</span></pre>
<p>
One important proviso is that any arguments you pass to subroutines or
methods must also be literal values or compile time constants.
</p>
<p>
For example, these are both fine:
</p>
<pre># literal argument
<span class="tt">[% constants.col.keys.sort.join(', ') %]</span>
# constant argument
<span class="tt">[% constants.col.keys.sort.join(constants.joint) %]</span></pre>
<p>
But this next example will raise an error at parse time because
<code>joint</code> is a runtime variable and cannot be determined at
compile time.
</p>
<pre># ERROR: runtime variable argument!
<span class="tt">[% constants.col.keys.sort.join(joint) %]</span></pre>
<p>
The <code>CONSTANTS_NAMESPACE</code> option can be used to provide a
different namespace prefix for constant variables. For example:
</p>
<pre>my $tt = Template->new({
CONSTANTS => {
version => 3.14,
# ...etc...
},
CONSTANTS_NAMESPACE => 'const',
});</pre>
<p>
Constants would then be referenced in templates as:
</p>
<pre><span class="tt">[% const.version %]</span></pre>
</div>
</div>
<div class="section">
<div class="head">
<h1 id="Special_Variables" onclick="switch_section(this)" title="Click title to show/hide section content.">Special Variables</h1>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
A number of special variables are automatically defined by the Template
Toolkit.
</p>
<div class="subsection">
<div class="head">
<h2 id="section_template" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">template</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
The <code>template</code> variable contains a reference to the main
template being processed, in the form of a <a href="../modules/Template/Document.html">Template::Document</a> object. This
variable is correctly defined within <code>PRE_PROCESS</code>,
<code>PROCESS</code> and <code>POST_PROCESS</code> templates, allowing
standard headers, footers, etc., to access metadata items from the main
template. The <code>name</code> and <code>modtime</code> metadata items
are automatically provided, giving the template name and modification
time in seconds since the epoch.
</p>
<p>
Note that the <code>template</code> variable always references the
top-level template, even when processing other template components via
<code>INCLUDE</code>, <code>PROCESS</code>, etc.
</p>
</div>
</div> <div class="subsection">
<div class="head">
<h2 id="section_component" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">component</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
The <code>component</code> variable is like <code>template</code> but
always contains a reference to the current, innermost template component
being processed. In the main template, the <code>template</code> and
<code>component</code> variable will reference the same <a href="../modules/Template/Document.html">Template::Document</a> object. In
any other template component called from the main template, the
<code>template</code> variable will remain unchanged, but
<code>component</code> will contain a new reference to the current
component.
</p>
<p>
This example should demonstrate the difference:
</p>
<pre>$template->process('foo')
|| die $template->error(), "\n";</pre>
<p>
<i>foo</i> template:
</p>
<pre><span class="tt">[% template.name %]</span> # foo
<span class="tt">[% component.name %]</span> # foo
<span class="tt">[% PROCESS footer %]</span></pre>
<p>
<i>footer</i> template:
</p>
<pre><span class="tt">[% template.name %]</span> # foo
<span class="tt">[% component.name %]</span> # footer</pre>
<p>
Additionally, the <code>component</code> variable has two special fields:
<code>caller</code> and <code>callers</code>. <code>caller</code>
contains the name of the template that called the current template (or
undef if the values of <code>template</code> and <code>component</code>
are the same). <code>callers</code> contains a reference to a list of all
the templates that have been called on the road to calling the current
component template (like a call stack), with the outer-most template
first.
</p>
<p>
Here's an example:
</p>
<p>
<i>outer.tt2</i> template:
</p>
<pre><span class="tt">[% component.name %]</span> # 'outer.tt2'
<span class="tt">[% component.caller %]</span> # undef
<span class="tt">[% component.callers %]</span> # undef
<span class="tt">[% PROCESS 'middle.tt2' %]</span></pre>
<p>
<i>middle.tt2</i> template:
</p>
<pre><span class="tt">[% component.name %]</span> # 'middle.tt2'
<span class="tt">[% component.caller %]</span> # 'outer.tt2'
<span class="tt">[% component.callers %]</span> # [ 'outer.tt2' ]
<span class="tt">[% PROCESS 'inner.tt2' %]</span></pre>
<p>
<i>inner.tt2</i> template:
</p>
<pre><span class="tt">[% component.name %]</span> # 'inner.tt2'
<span class="tt">[% component.caller %]</span> # 'middle.tt2'
<span class="tt">[% component.callers %]</span> # [ 'outer.tt2', 'middle.tt2' ]</pre>
</div>
</div> <div class="subsection">
<div class="head">
<h2 id="section_loop" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">loop</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
Within a <code>FOREACH</code> loop, the <code>loop</code> variable
references the <a href="../modules/Template/Iterator.html">Template::Iterator</a> object responsible for controlling the loop.
</p>
<pre><span class="tt">[% FOREACH item = [ 'foo', 'bar', 'baz' ] -%]</span>
<span class="tt">[% "Items:\n" IF loop.first -%]</span>
<span class="tt">[% loop.count %]</span>/<span class="tt">[% loop.size %]</span>: <span class="tt">[% item %]</span>
<span class="tt">[% END %]</span></pre>
</div>
</div> <div class="subsection">
<div class="head">
<h2 id="section_error" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">error</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
Within a <code>CATCH</code> block, the <code>error</code> variable
contains a reference to the <a href="../modules/Template/Exception.html">Template::Exception</a> object thrown from within the
<code>TRY</code> block. The <code>type</code> and <code>info</code>
methods can be called or the variable itself can be printed for automatic
stringification into a message of the form "<code>$type error -
$info</code>". See <a href="../modules/Template/Exception.html">Template::Exception</a> for further details.
</p>
<pre><span class="tt">[% TRY %]</span>
...
<span class="tt">[% CATCH %]</span>
<span class="tt">[% error %]</span>
<span class="tt">[% END %]</span></pre>
</div>
</div> <div class="subsection">
<div class="head">
<h2 id="section_content" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">content</h2>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
The <code>WRAPPER</code> method captures the output from a template block
and then includes a named template, passing the captured output as the
'content' variable.
</p>
<pre><span class="tt">[% WRAPPER box %]</span>
Be not afeard; the isle is full of noises,
Sounds and sweet airs, that give delight and hurt not.
<span class="tt">[% END %]</span>
<span class="tt">[% BLOCK box %]</span>
<blockquote class="prose">
<span class="tt">[% content %]</span>
</blockquote>
<span class="tt">[% END %]</span></pre>
</div>
</div>
</div>
</div>
<div class="section">
<div class="head">
<h1 id="Compound_Variables" onclick="switch_section(this)" title="Click title to show/hide section content.">Compound Variables</h1>
<a href="#body" class="top" title="Back up to the top of the page" >Top</a>
</div>
<div class="body">
<p>
Compound 'dotted' variables may contain any number of separate elements.
Each element may evaluate to any of the permitted variable types and the
processor will then correctly use this value to evaluate the rest of the
variable. Arguments may be passed to any of the intermediate elements.
</p>
<pre><span class="tt">[% myorg.people.sort('surname').first.fullname %]</span></pre>
<p>
Intermediate variables may be used and will behave entirely as expected.
</p>
<pre><span class="tt">[% sorted = myorg.people.sort('surname') %]</span>
<span class="tt">[% sorted.first.fullname %]</span></pre>
<p>
This simplified dotted notation has the benefit of hiding the
implementation details of your data. For example, you could implement a
data structure as a hash array one day and then change it to an object
the next without requiring any change to the templates.
</p>
</div>
</div>
</div></div>
<br class="clear" />
<div class="pageinfo">
<a href="http://template-toolkit.org/docs/manual/Variables.html">http://template-toolkit.org/docs/manual/Variables.html</a>
</div>
</div>
<div id="footer">
<a href="http://opensource.org/" class="osi"></a>
<div class="controls">
<div class="pager">
<a href="../manual/Directives.html" title="Template::Manual::Directives" class="go back">Back<span class="about"><h4>Template::Manual::Directives</h4></span></a>
<a href="../manual/index.html" title="Template::Manual" class="go up">Up<span class="about"><h4>Template::Manual</h4></span></a>
<a href="../manual/VMethods.html" title="Template::Manual::VMethods" class="go next">Next<span class="about"><h4>Template::Manual::VMethods</h4></span></a>
</div>
</div>
<div class="copyright">
Copyright © 1996-2012 <a href="http://wardley.org/">Andy Wardley</a>. All Rights Reserved.
</div>
<div class="licence">
The <a href="http://template-toolkit.org/">Template Toolkit</a> is <a href="http://opensource.org/">Open Source</a> software.
You can redistribute and/or modify it under the terms of the <a href="http://www.opensource.org/licenses/gpl-license.php">GNU Public Licence</a>
or the <a href="http://www.opensource.org/licenses/artistic-license.php">Perl Artistic Licence</a>.
</div>
</div>
<div id="palette">
<ul>
<li class="first"><a href="#" class="blue" onclick="set_style('Clear Blue')"></a></li>
<li><a href="#" class="orange" onclick="set_style('Clear Orange')"></a></li>
<li><a href="#" class="green" onclick="set_style('Clear Green')"></a></li>
<li><a href="#" class="purple" onclick="set_style('Clear Purple')"></a></li>
<li><a href="#" class="grey" onclick="set_style('Clear Grey')"></a></li>
</ul>
</div>
</div> </body>
</html>
|