-
Notifications
You must be signed in to change notification settings - Fork 94
/
Variables.html
867 lines (856 loc) · 31.1 KB
/
Variables.html
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
[%#
# IMPORTANT NOTE
# This documentation is generated automatically from source
# templates. Any changes you make here may be lost.
#
# The 'docsrc' documentation source bundle is available for download
# from http://www.template-toolkit.org/docs.html and contains all
# the source templates, XML files, scripts, etc., from which the
# documentation for the Template Toolkit is built.
-%]
[% META book = 'Manual'
page = 'Variables'
%]
[% WRAPPER toc;
PROCESS tocitem
title ="DESCRIPTION"
subs = [
"Template Variables",
"Scalar Values",
"Hash Array References",
"List References",
"Subroutines",
"Objects",
"Parameters and Return Values",
"Error Handling",
"Virtual Methods",
"Variable Interpolation",
"Local and Global Variables",
"Compile Time Constant Folding",
"Special Variables",
"Compound Variables"
];
PROCESS tocitem
title ="AUTHOR"
subs = [];
PROCESS tocitem
title ="VERSION"
subs = [];
PROCESS tocitem
title ="COPYRIGHT"
subs = [];
END
%]
<!-- Pod to HTML conversion by the Template Toolkit version 2 -->
[% WRAPPER section
title="DESCRIPTION"
-%]<p>
This section describes the different ways in which Perl data can be
bound to template variables and accessed via Template Toolkit
directives.
</p>
[% WRAPPER subsection
title = "Template Variables"
-%]<p>
A reference to a hash array may be passed as the second argument to
the process() method, containing definitions of template variables.
The VARIABLES (a.k.a. PRE_DEFINE) 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',
},
});</pre>
<pre> my $vars = {
serial_no => 271828,
};</pre>
<pre> $tt->process('myfile', $vars);</pre>
<p>
'myfile':
</p>
<pre> This is version [% tt_start_tag %] version [% tt_end_tag %] ([% tt_start_tag %] release [% tt_end_tag %]).
Serial number: [% tt_start_tag %] serial_no [% tt_end_tag %]</pre>
<p>
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 'foo',
'Foo' and 'FOO' 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:
</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>
template:
</p>
<pre> [% tt_start_tag %] article [% tt_end_tag %]</pre>
<pre> [% tt_start_tag %] person.id [% tt_end_tag %]: [% tt_start_tag %] person.name [% tt_end_tag %] <[% tt_start_tag %] person.email [% tt_end_tag %]></pre>
<pre> [% tt_start_tag %] primes.first [% tt_end_tag %] - [% tt_start_tag %] primes.last [% tt_end_tag %], including [% tt_start_tag %] primes.3 [% tt_end_tag %]
[% tt_start_tag %] primes.size [% tt_end_tag %] prime numbers: [% tt_start_tag %] primes.join(', ') [% tt_end_tag %]</pre>
<pre> [% tt_start_tag %] wizard [% tt_end_tag %]
[% tt_start_tag %] wizard('Hocus Pocus!') [% tt_end_tag %]</pre>
<pre> [% tt_start_tag %] cgi.param('mode') [% tt_end_tag %]</pre>
<p>
output:
</p>
<pre> The Third Shoe</pre>
<pre> 314: Mr. Blue <blue@nowhere.org></pre>
<pre> 2 - 13, including 7
6 prime numbers: 2, 3, 5, 7, 11, 13</pre>
<pre> Abracadabra!
Abracadabra! Hocus Pocus!
submit</pre>
[%- END %]
[% WRAPPER subsection
title = "Scalar Values"
-%]<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> [% tt_start_tag %] article [% tt_end_tag %]</pre>
[%- END %]
[% WRAPPER subsection
title = "Hash Array References"
-%]<p>
Members of hash arrays are accessed by specifying the hash reference
and key separated by the dot '.' operator.
</p>
<pre> my $vars = {
'home' => 'http://www.myserver.com/homepage.html',
'page' => {
'this' => 'mypage.html',
'next' => 'nextpage.html',
'prev' => 'prevpage.html',
},
};</pre>
<p>
template:
</p>
<pre> <a href="[% tt_start_tag %] home [% tt_end_tag %]">Home</a>
<a href="[% tt_start_tag %] page.prev [% tt_end_tag %]">Previous Page</a>
<a href="[% tt_start_tag %] page.next [% tt_end_tag %]">Next Page</a></pre>
<p>
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 '_' or '.' 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
DEBUG option is enabled).
</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>
template:
</p>
<pre> [% tt_start_tag %] message [% tt_end_tag %] # outputs "Hello World!"
[% tt_start_tag %] _secret [% tt_end_tag %] # no output
[% tt_start_tag %] thing.public [% tt_end_tag %] # outputs "123"
[% tt_start_tag %] thing._private [% tt_end_tag %] # no output
[% tt_start_tag %] thing..hidden [% tt_end_tag %] # ERROR: unexpected token (..)</pre>
<p>
To access a hash entry using a key stored in another variable, prefix
the key variable with '$' to have it interpolated before use (see
[% ttlink('Variable Interpolation') -%]).
</p>
<pre> [% tt_start_tag %] pagename = 'next' [% tt_end_tag %]
[% tt_start_tag %] page.$pagename [% tt_end_tag %] # same as [% tt_start_tag %] page.next [% tt_end_tag %]</pre>
<p>
When you assign to a variable that contains multiple namespace
elements (i.e. it has one or more '.' characters in the name),
any hashes required to represent intermediate namespaces will be
created automatically. In this following example, the 'product'
variable automatically springs into life as a hash array unless
otherwise defined.
</p>
<pre> [% tt_start_tag %] product.id = 'XYZ-2000'
product.desc = 'Bogon Generator'
product.price = 666
[% tt_end_tag %]
The [% tt_start_tag %] product.id [% tt_end_tag %] [% tt_start_tag %] product.desc [% tt_end_tag %]
costs $[% tt_start_tag %] product.price [% tt_end_tag %].00</pre>
<p>
output:
</p>
<pre> The XYZ-2000 Bogon Generator
costs $666.00</pre>
<p>
You can use Perl's familiar '{' ... '}' construct to explicitly create
a hash and assign it to a variable. Note that commas are optional
between key/value pairs and '=' can be used in place of '=>'.
</p>
<pre> [% tt_start_tag %] product = {
id => 'XYZ-2000',
desc => 'Bogon Generator',
price => 666,
}
[% tt_end_tag %]</pre>
[%- END %]
[% WRAPPER subsection
title = "List References"
-%]<p>
Items in lists are also accessed by use of the dot operator.
</p>
<pre> my $vars = {
'people' => [ 'Tom', 'Dick', 'Larry' ],
};</pre>
<p>
template:
</p>
<pre> [% tt_start_tag %] people.0 [% tt_end_tag %] # Tom
[% tt_start_tag %] people.1 [% tt_end_tag %] # Dick
[% tt_start_tag %] people.2 [% tt_end_tag %] # Larry</pre>
<p>
The FOREACH directive can be used to iterate through items in a list.
</p>
<pre> [% tt_start_tag %] FOREACH person = people [% tt_end_tag %]
Hello [% tt_start_tag %] person [% tt_end_tag %]
[% tt_start_tag %] END [% tt_end_tag %]</pre>
<p>
output:
</p>
<pre> Hello Tom
Hello Dick
Hello Larry</pre>
<p>
Lists can be constructed in-situ using the regular anonymous list
'[' ... ']' construct. Commas between items are optional.
</p>
<pre> [% tt_start_tag %] cols = [ 'red', 'green', 'blue' ] [% tt_end_tag %]</pre>
<pre> [% tt_start_tag %] FOREACH c = cols [% tt_end_tag %]
...</pre>
<p>
or:
</p>
<pre> [% tt_start_tag %] FOREACH c = [ 'red', 'green', 'blue' ] [% tt_end_tag %]
...</pre>
<p>
You can also create simple numerical sequences using the familiar '..'
operator:
</p>
<pre> [% tt_start_tag %] n = [ 1 .. 4 ] [% tt_end_tag %] # n is [ 1, 2, 3, 4 ] </pre>
<pre> [% tt_start_tag %] x = 4
y = 8
z = [x..y] # z is [ 4, 5, 6, 7, 8 ]
[% tt_end_tag %]</pre>
[%- END %]
[% WRAPPER subsection
title = "Subroutines"
-%]<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>
template:
</p>
<pre> [% tt_start_tag %] wizard [% tt_end_tag %] # Abracadabra!
[% tt_start_tag %] wizard('Hocus Pocus!') [% tt_end_tag %] # Abracadabra! Hocus Pocus!</pre>
[%- END %]
[% WRAPPER subsection
title = "Objects"
-%]<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;</pre>
<pre> ...</pre>
<pre> my $vars = {
# hard coded CGI params for purpose of example
cgi => CGI->new('mode=submit&debug=1'),
};</pre>
<p>
template:
</p>
<pre> [% tt_start_tag %] FOREACH p = cgi.param [% tt_end_tag %] # returns list of param keys
[% tt_start_tag %] p [% tt_end_tag %] => [% tt_start_tag %] cgi.param(p) [% tt_end_tag %] # fetch each param value
[% tt_start_tag %] END [% tt_end_tag %]</pre>
<p>
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> [% tt_start_tag %] myobj.method = 10 [% tt_end_tag %]</pre>
<p>
equivalent to:
</p>
<pre> [% tt_start_tag %] myobj.method(10) [% tt_end_tag %]</pre>
[%- END %]
[% WRAPPER subsection
title = "Parameters and Return Values"
-%]<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> [% tt_start_tag %] foo = 10 [% tt_end_tag %]
[% tt_start_tag %] mycode(foo, 20) [% tt_end_tag %] # 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 '=>' or '=' and can appear anywhere in the argument list.
</p>
<pre> my $vars = {
myjoin => \&myjoin,
};</pre>
<pre> sub myjoin {
# look for hash ref as last argument
my $params = ref $_[-1] eq 'HASH' ? pop : { };
return join($params->{ joint } || ' + ', @_);
}</pre>
<p>
template:
</p>
<pre> [% tt_start_tag %] myjoin(10, 20, 30) [% tt_end_tag %]
[% tt_start_tag %] myjoin(10, 20, 30, joint = ' - ' [% tt_end_tag %]
[% tt_start_tag %] myjoin(joint => ' * ', 10, 20, 30 [% tt_end_tag %]</pre>
<p>
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> [% tt_start_tag %] r = 'Romeo' [% tt_end_tag %]
[% tt_start_tag %] r(100, 99, s, t, v) [% tt_end_tag %] # 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>
template:
</p>
<pre> [% tt_start_tag %] FOREACH i = items1 [% tt_end_tag %]
...
[% tt_start_tag %] END [% tt_end_tag %]</pre>
<pre> [% tt_start_tag %] FOREACH i = items2 [% tt_end_tag %]
...
[% tt_start_tag %] END [% tt_end_tag %]</pre>
[%- END %]
[% WRAPPER subsection
title = "Error Handling"
-%]<p>
Errors can be reported from user code by calling die(). 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 'error'
variable.
</p>
<pre> my $vars = {
barf => sub {
die "a sick error has occurred\n";
},
};</pre>
<p>
template:
</p>
<pre> [% tt_start_tag %] TRY [% tt_end_tag %]
[% tt_start_tag %] barf [% tt_end_tag %] # calls sub which throws error via die()
[% tt_start_tag %] CATCH [% tt_end_tag %]
[% tt_start_tag %] error.info [% tt_end_tag %] # outputs "a sick error has occurred\n"
[% tt_start_tag %] END [% tt_end_tag %]</pre>
<p>
Error messages thrown via die() are converted to exceptions of type
'undef'. Exceptions of user-defined types can be thrown by calling
die() with a reference to a Template::Exception object.
</p>
<pre> use Template::Exception;</pre>
<pre> ...
my $vars = {
login => sub {
...
die Template::Exception->new('badpwd',
'password too silly');
},
};</pre>
<p>
template:
</p>
<pre> [% tt_start_tag %] TRY [% tt_end_tag %]
[% tt_start_tag %] login [% tt_end_tag %]
[% tt_start_tag %] CATCH badpwd [% tt_end_tag %]
Bad password: [% tt_start_tag %] error.info [% tt_end_tag %]
[% tt_start_tag %] CATCH [% tt_end_tag %]
Some other '[% tt_start_tag %] error.type [% tt_end_tag %]' error: [% tt_start_tag %] error.info [% tt_end_tag %]
[% tt_start_tag %] END [% tt_end_tag %]</pre>
<p>
The exception types 'stop' and 'return' are used to implement the
STOP and RETURN directives. Throwing an exception as:
</p>
<pre> die (Template::Exception->new('stop'));</pre>
<p>
has the same effect as the directive:
</p>
<pre> [% tt_start_tag %] STOP [% tt_end_tag %]</pre>
<p>
Subroutines and methods can also raise errors by returning a list or
reference to a list containing the undefined value (undef) followed by
an exception object or error message. This is supported for backwards
compatibility with version 1 but may be deprecated in some future
version.
</p>
<pre> my $vars = {
# currently equivalent
barf => sub {
die "I'm sorry Dave, I can't do that";
},
yack => sub {
return (undef, "I'm sorry Dave, I can't do that");
},
};</pre>
[%- END %]
[% WRAPPER subsection
title = "Virtual Methods"
-%]<p>
The Template Toolkit implements a number of "virtual methods" which
can be applied to scalars, hashes or lists. For example:
</p>
<pre> [% tt_start_tag %] mylist = [ 'foo', 'bar', 'baz' ] [% tt_end_tag %]
[% tt_start_tag %] newlist = mylist.sort [% tt_end_tag %]</pre>
<p>
Here 'mylist' 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> [% tt_start_tag %] mylist.sort.join(', ') [% tt_end_tag %]</pre>
<p>
Here the 'join' 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 [% ttlink('Template::Manual::VMethods') -%] for details of all the virtual
methods available.
</p>
[%- END %]
[% WRAPPER subsection
title = "Variable Interpolation"
-%]<p>
The Template Toolkit uses '$' consistently to indicate that a variable
should be interpolated in position. Most frequently, you see this in
double-quoted strings:
</p>
<pre> [% tt_start_tag %] fullname = "$honorific $firstname $surname" [% tt_end_tag %]</pre>
<p>
Or embedded in plain text when the INTERPOLATE option is set:
</p>
<pre> Dear $honorific $firstname $surname,</pre>
<p>
The same rules apply within directives. If a variable is prefixed
with a '$' 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> [% tt_start_tag %] uid = 'abw' [% tt_end_tag %]
[% tt_start_tag %] userlist.$uid [% tt_end_tag %] # same as 'userlist.abw'</pre>
<p>
Curly braces can be used to delimit interpolated variable names where
necessary.
</p>
<pre> [% tt_start_tag %] userlist.${me.id}.name [% tt_end_tag %] </pre>
<p>
Directives such as INCLUDE, PROCESS, etc., that accept a template name
as the first argument, will automatically quote it for convenience.
</p>
<pre> [% tt_start_tag %] INCLUDE foo/bar.txt [% tt_end_tag %]</pre>
<p>
equivalent to:
</p>
<pre> [% tt_start_tag %] INCLUDE "foo/bar.txt" [% tt_end_tag %]</pre>
<p>
To INCLUDE a template whose name is stored in a variable, simply
prefix the variable name with '$' to have it interpolated.
</p>
<pre> [% tt_start_tag %] myfile = 'header' [% tt_end_tag %]
[% tt_start_tag %] INCLUDE $myfile [% tt_end_tag %]</pre>
<p>
equivalent to:
</p>
<pre> [% tt_start_tag %] INCLUDE header [% tt_end_tag %]</pre>
<p>
Note also that a variable containing a reference to a Template::Document
object can also be processed in this way.
</p>
<pre> my $vars = {
header => Template::Document->new({ ... }),
};</pre>
<p>
template:
</p>
<pre> [% tt_start_tag %] INCLUDE $header [% tt_end_tag %]</pre>
[%- END %]
[% WRAPPER subsection
title = "Local and Global Variables"
-%]<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. The same thing happens when you INCLUDE another
template. The current namespace hash is cloned to prevent any
variable changes made in the included template from interfering with
existing variables. The PROCESS 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> [% tt_start_tag %] BLOCK change_name [% tt_end_tag %]
[% tt_start_tag %] name = 'bar' [% tt_end_tag %]
[% tt_start_tag %] END [% tt_end_tag %]</pre>
<pre> [% tt_start_tag %] name = 'foo' [% tt_end_tag %]
[% tt_start_tag %] INCLUDE change_name [% tt_end_tag %]
[% tt_start_tag %] name [% tt_end_tag %] # foo
[% tt_start_tag %] PROCESS change_name [% tt_end_tag %]
[% tt_start_tag %] name [% tt_end_tag %] # 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> [% tt_start_tag %] BLOCK all_change [% tt_end_tag %]
[% tt_start_tag %] x = 20 [% tt_end_tag %] # changes copy
[% tt_start_tag %] y.z = 'zulu' [% tt_end_tag %] # changes original
[% tt_start_tag %] END [% tt_end_tag %]</pre>
<pre> [% tt_start_tag %] x = 10
y = { z => 'zebra' }
[% tt_end_tag %]
[% tt_start_tag %] INCLUDE all_change [% tt_end_tag %]
[% tt_start_tag %] x [% tt_end_tag %] # still '10'
[% tt_start_tag %] y.z [% tt_end_tag %] # 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> [% tt_start_tag %] BLOCK new_stuff [% tt_end_tag %]
[% tt_start_tag %] # define a new 'y' hash array in local context
y = { z => 'zulu' }
[% tt_end_tag %]
[% tt_start_tag %] END [% tt_end_tag %]</pre>
<pre> [% tt_start_tag %] x = 10 [% tt_end_tag %]
[% tt_start_tag %] INCLUDE new_stuff [% tt_end_tag %]
[% tt_start_tag %] x [% tt_end_tag %] # outputs '10'
[% tt_start_tag %] y [% tt_end_tag %] # 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> [% tt_start_tag %] BLOCK new_stuff [% tt_end_tag %]
[% tt_start_tag %] y.z = 'zulu' [% tt_end_tag %]
[% tt_start_tag %] END [% tt_end_tag %]</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> [% tt_start_tag %] global.version = 123 [% tt_end_tag %]</pre>
[%- END %]
[% WRAPPER subsection
title = "Compile Time Constant Folding"
-%]<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 CONSTANTS hash as a
constructor item as per VARIABLES. The CONSTANTS 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 'constants'
namespace prefix.
</p>
<pre> Version [% tt_start_tag %] constants.version [% tt_end_tag %] ([% tt_start_tag %] constants.release [% tt_end_tag %])</pre>
<pre> Background: [% tt_start_tag %] constants.col.back [% tt_end_tag %]</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> [% tt_start_tag %] constants.mysub(10, 20) [% tt_end_tag %]
[% tt_start_tag %] constants.myobj(30, 40) [% tt_end_tag %]
[% tt_start_tag %] constants.col.keys.sort.join(', ') [% tt_end_tag %]</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
[% tt_start_tag %] constants.col.keys.sort.join(', ') [% tt_end_tag %]</pre>
<pre> # constant argument
[% tt_start_tag %] constants.col.keys.sort.join(constants.joint) [% tt_end_tag %]</pre>
<p>
But this next example will raise an error at parse time because
'joint' is a runtime variable and cannot be determined at compile
time.
</p>
<pre> # ERROR: runtime variable argument!
[% tt_start_tag %] constants.col.keys.sort.join(joint) [% tt_end_tag %]</pre>
<p>
The CONSTANTS_NAMESPACE 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> [% tt_start_tag %] const.version [% tt_end_tag %]</pre>
[%- END %]
[% WRAPPER subsection
title = "Special Variables"
-%]<p>
A number of special variables are automatically defined by the Template
Toolkit.
</p>
<ul>
<li><b>template</b><br>
<p>
The 'template' variable contains a reference to the main template
being processed, in the form of a Template::Document object. This
variable is correctly defined within PRE_PROCESS, PROCESS and
POST_PROCESS templates, allowing standard headers, footers, etc., to
access metadata items from the main template. The 'name' and
'modtime' metadata items are automatically provided, giving the
template name and modification time in seconds since the epoch.
</p>
<p>
Note that the 'template' variable always references the top-level
template, even when processing other template components via INCLUDE,
PROCESS, etc.
</p>
<li><b>component</b><br>
<p>
The 'component' variable is like 'template' but always contains a
reference to the current, innermost template component being processed.
In the main template, the 'template' and 'component' variable will
reference the same Template::Document object. In any other template
component called from the main template, the 'template' variable
will remain unchanged, but 'component' 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>
'foo':
</p>
<pre> [% tt_start_tag %] template.name [% tt_end_tag %] # foo
[% tt_start_tag %] component.name [% tt_end_tag %] # foo
[% tt_start_tag %] PROCESS footer [% tt_end_tag %]</pre>
<p>
'footer':
</p>
<pre> [% tt_start_tag %] template.name [% tt_end_tag %] # foo
[% tt_start_tag %] component.name [% tt_end_tag %] # footer</pre>
<li><b>loop</b><br>
<p>
Within a FOREACH loop, the 'loop' variable references the Template::Iterator
object responsible for controlling the loop.
</p>
<pre> [% tt_start_tag %] FOREACH item = [ 'foo', 'bar', 'baz' ] -[% tt_end_tag %]
[% tt_start_tag %] "Items:\n" IF loop.first -[% tt_end_tag %]
[% tt_start_tag %] loop.count [% tt_end_tag %]/[% tt_start_tag %] loop.size [% tt_end_tag %]: [% tt_start_tag %] item [% tt_end_tag %]
[% tt_start_tag %] END [% tt_end_tag %]</pre>
<li><b>error</b><br>
<p>
Within a CATCH block, the 'error' variable contains a reference to the
Template::Exception object thrown from within the TRY block. The
'type' and 'info' methods can be called or the variable itself can
be printed for automatic stringification into a message of the form
"$type error - $info". See [% ttlink('Template::Exception') -%] for further details.
</p>
<pre> [% tt_start_tag %] TRY [% tt_end_tag %]
...
[% tt_start_tag %] CATCH [% tt_end_tag %]
[% tt_start_tag %] error [% tt_end_tag %]
[% tt_start_tag %] END [% tt_end_tag %]</pre>
<li><b>content</b><br>
<p>
The WRAPPER method captures the output from a template block and then
includes a named template, passing the captured output as the 'content'
variable.
</p>
<pre> [% tt_start_tag %] WRAPPER box [% tt_end_tag %]
Be not afeard; the isle is full of noises,
Sounds and sweet airs, that give delight and hurt not.
[% tt_start_tag %] END [% tt_end_tag %]</pre>
<pre> [% tt_start_tag %] BLOCK box [% tt_end_tag %]
<table border=1>
<tr>
<td>
[% tt_start_tag %] content [% tt_end_tag %]
</td>
</tr>
</table>
[% tt_start_tag %] END [% tt_end_tag %]</pre>
</ul>
[%- END %]
[% WRAPPER subsection
title = "Compound Variables"
-%]<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> [% tt_start_tag %] myorg.people.sort('surname').first.fullname [% tt_end_tag %]</pre>
<p>
Intermediate variables may be used and will behave entirely as expected.
</p>
<pre> [% tt_start_tag %] sorted = myorg.people.sort('surname') [% tt_end_tag %]
[% tt_start_tag %] sorted.first.fullname [% tt_end_tag %]</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>
[%- END %]
[%- END %]
[% WRAPPER section
title="AUTHOR"
-%]<p>
Andy Wardley <abw@andywardley.com>
</p>
<p>
[% ttlink('http://www.andywardley.com/', 'http://www.andywardley.com/') -%]
</p>
[%- END %]
[% WRAPPER section
title="VERSION"
-%]<p>
Template Toolkit version 2.13, released on 30 January 2004.
</p>
[%- END %]
[% WRAPPER section
title="COPYRIGHT"
-%]<pre> Copyright (C) 1996-2004 Andy Wardley. All Rights Reserved.
Copyright (C) 1998-2002 Canon Research Centre Europe Ltd.</pre>
<p>
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
</p>
[%- END %]