Add built local::lib
[catagits/Gitalist.git] / local-lib5 / lib / perl5 / i486-linux-gnu-thread-multi / Template / Manual / Directives.pod
1 #============================================================= -*-perl-*-
2 #
3 # Template::Manual::Directives
4 #
5 # AUTHOR
6 #   Andy Wardley  <abw@wardley.org>
7 #
8 # COPYRIGHT
9 #   Copyright (C) 1996-2007 Andy Wardley.  All Rights Reserved.
10 #
11 #   This module is free software; you can redistribute it and/or
12 #   modify it under the same terms as Perl itself.
13 #
14 #========================================================================
15
16 =head1 NAME
17
18 Template::Manual::Directives - Template directives
19
20 =head1 Accessing and Updating Template Variables
21
22 =head2 GET
23
24 The C<GET> directive retrieves and outputs the value of the named variable.
25
26     [% GET foo %]
27
28 The C<GET> keyword is optional.  A variable can be specified in a directive
29 tag by itself.
30
31     [% foo %]
32
33 The variable can have an unlimited number of elements, each separated by a
34 dot. Each element can have arguments specified within parentheses.
35
36     [% foo %]
37     [% bar.baz %]
38     [% biz.baz(10) %]
39     ...etc...
40
41 See L<Template::Manual::Variables> for a full discussion on template
42 variables.
43
44 You can also specify expressions using the logical (C<and>, C<or>, C<not>, C<?>, C<:>) and
45 mathematic operators (C<+>, C<->, C<*>, C</>, C<%>, C<mod>, C<div>).
46
47     [% template.title or default.title %]
48     
49     [% score * 100 %]
50     
51     [% order.nitems ? checkout(order.total) : 'no items' %]
52
53 The C<div> operator returns the integer result of division.  Both C<%> and 
54 C<mod> return the modulus (i.e. remainder) of division. 
55
56     [% 15 / 6 %]            # 2.5
57     [% 15 div 6 %]          # 2
58     [% 15 mod 6 %]          # 3
59
60 =head2 CALL
61
62 The C<CALL> directive is similar to C<GET> in evaluating the variable named,
63 but doesn't print the result returned.  This can be useful when a
64 variable is bound to a sub-routine or object method which you want to
65 call but aren't interested in the value returned.
66
67     [% CALL dbi.disconnect %]
68     
69     [% CALL inc_page_counter(page_count) %]
70
71 =head2 SET
72
73 The C<SET> directive allows you to assign new values to existing variables
74 or create new temporary variables.
75
76     [% SET title = 'Hello World' %]
77
78 The C<SET> keyword is also optional.
79    
80     [% title = 'Hello World' %]
81
82 Variables may be assigned the values of other variables, unquoted
83 numbers (2.718), literal text ('single quotes') or quoted text
84 ("double quotes").  In the latter case, any variable references within
85 the text will be interpolated when the string is evaluated.  Variables
86 should be prefixed by C<$>, using curly braces to explicitly scope
87 the variable name where necessary.
88
89     [% foo  = 'Foo'  %]               # literal value 'Foo'
90     [% bar  =  foo   %]               # value of variable 'foo'
91     [% cost = '$100' %]               # literal value '$100'
92     [% item = "$bar: ${cost}.00" %]   # value "Foo: $100.00"
93
94 Multiple variables may be assigned in the same directive and are 
95 evaluated in the order specified.  Thus, the above could have been 
96 written:
97
98     [% foo  = 'Foo'
99        bar  = foo
100        cost = '$100'
101        item = "$bar: ${cost}.00"
102     %]
103
104 Simple expressions can also be used, as per C<GET>.
105
106     [% ten    = 10 
107        twenty = 20
108        thirty = twenty + ten
109        forty  = 2 * twenty 
110        fifty  = 100 div 2
111        six    = twenty mod 7
112     %]
113
114 You can concatenate strings together using the C<' _ '> operator.  In Perl 5,
115 the C<.> is used for string concatenation, but in Perl 6, as in the Template
116 Toolkit, the C<.> will be used as the method calling operator and C<' _ '> will
117 be used for string concatenation.  Note that the operator must be 
118 specified with surrounding whitespace which, as Larry says, is construed as
119 a feature:
120
121     [% copyright = '(C) Copyright' _ year _ ' ' _ author %]
122
123 You can, of course, achieve a similar effect with double quoted string 
124 interpolation.
125
126     [% copyright = "(C) Copyright $year $author" %]
127
128 =head2 DEFAULT
129
130 The C<DEFAULT> directive is similar to C<SET> but only updates variables 
131 that are currently undefined or have no "true" value (in the Perl
132 sense).
133
134     [% DEFAULT
135         name = 'John Doe'
136         id   = 'jdoe'
137     %]
138
139 This can be particularly useful in common template components to
140 ensure that some sensible default are provided for otherwise 
141 undefined variables.
142
143     [% DEFAULT 
144        title = 'Hello World'
145        bgcol = '#ffffff'
146     %]
147     <html>
148       <head>
149         <title>[% title %]</title>
150       </head>
151       <body bgcolor="[% bgcol %]">
152         ...etc...
153
154 =head1 Processing Template Files and Blocks
155
156 =head2 INSERT
157
158 The C<INSERT> directive is used to insert the contents of an external file
159 at the current position.
160
161     [% INSERT myfile %]
162
163 No attempt to parse or process the file is made.  The contents,
164 possibly including any embedded template directives, are inserted
165 intact.
166
167 The filename specified should be relative to one of the C<INCLUDE_PATH>
168 directories.  Absolute (i.e. starting with C</>) and relative
169 (i.e. starting with C<.>) filenames may be used if the C<ABSOLUTE> and
170 C<RELATIVE> options are set, respectively.  Both these options are
171 disabled by default.
172
173     my $template = Template->new({
174         INCLUDE_PATH => '/here:/there',
175     });
176     
177     $template->process('myfile');
178
179 F<myfile>:
180
181     [% INSERT foo %]            # looks for /here/foo then /there/foo
182     [% INSERT /etc/passwd %]    # file error: ABSOLUTE not set
183     [% INSERT ../secret %]      # file error: RELATIVE not set
184
185 For convenience, the filename does not need to be quoted as long as it
186 contains only alphanumeric characters, underscores, dots or forward
187 slashes.  Names containing any other characters should be quoted.
188
189     [% INSERT misc/legalese.txt            %]
190     [% INSERT 'dos98/Program Files/stupid' %]
191
192 To evaluate a variable to specify a filename, you should explicitly
193 prefix it with a C<$> or use double-quoted string interpolation.
194
195     [% language = 'en'
196        legalese = 'misc/legalese.txt' 
197     %]
198     
199     [% INSERT $legalese %]              # misc/legalese.txt
200     [% INSERT "$language/$legalese" %]  # en/misc/legalese.txt
201
202 Multiple files can be specified using C<+> as a delimiter.  All files
203 should be unquoted names or quoted strings.  Any variables should be
204 interpolated into double-quoted strings.
205
206     [% INSERT legalese.txt + warning.txt %]
207     [% INSERT  "$legalese" + warning.txt %]  # requires quoting
208
209 =head2 INCLUDE
210
211 The C<INCLUDE> directive is used to process and include the output of
212 another template file or block.
213
214     [% INCLUDE header %]
215
216 If a C<BLOCK> of the specified name is defined in the same file, or in a file
217 from which the current template has been called (i.e. a parent template) then
218 it will be used in preference to any file of the same name.
219
220     [% INCLUDE table %]     # uses BLOCK defined below
221     
222     [% BLOCK table %]
223        <table>
224          ...
225        </table>
226     [% END %]
227
228 If a C<BLOCK> definition is not currently visible then the template name
229 should be a file relative to one of the C<INCLUDE_PATH> directories, or
230 an absolute or relative file name if the C<ABSOLUTE>/C<RELATIVE> options are
231 appropriately enabled.  The C<INCLUDE> directive automatically quotes the
232 filename specified, as per C<INSERT> described above.  When a variable
233 contains the name of the template for the C<INCLUDE> directive, it should
234 be explicitly prefixed by C<$> or double-quoted
235
236     [% myheader = 'my/misc/header' %]
237     [% INCLUDE   myheader  %]           # 'myheader'
238     [% INCLUDE  $myheader  %]           # 'my/misc/header'
239     [% INCLUDE "$myheader" %]           # 'my/misc/header'
240
241 Any template directives embedded within the file will be processed
242 accordingly.  All variables currently defined will be visible and 
243 accessible from within the included template.  
244
245     [% title = 'Hello World' %]
246     [% INCLUDE header %]
247     <body>
248     ...
249
250 F<header>:
251
252     <html>
253     <title>[% title %]</title>
254
255 output:
256
257     <html>
258     <title>Hello World</title>
259     <body>
260     ...
261
262 Local variable definitions may be specified after the template name,
263 temporarily masking any existing variables.  Insignificant whitespace
264 is ignored within directives so you can add variable definitions on the
265 same line, the next line or split across several line with comments
266 interspersed, if you prefer.
267
268     [% INCLUDE table %]
269     
270     [% INCLUDE table title="Active Projects" %]
271     
272     [% INCLUDE table 
273          title   = "Active Projects" 
274          bgcolor = "#80ff00"    # chartreuse
275          border  = 2
276     %]
277
278 The C<INCLUDE> directive localises (i.e. copies) all variables before
279 processing the template.  Any changes made within the included
280 template will not affect variables in the including template.
281
282     [% foo = 10 %]
283     
284     foo is originally [% foo %]
285     [% INCLUDE bar %]
286     foo is still [% foo %]
287     
288     [% BLOCK bar %]
289        foo was [% foo %]
290        [% foo = 20 %]
291        foo is now [% foo %]
292     [% END %]
293
294 output:
295
296     foo is originally 10
297        foo was 10
298        foo is now 20
299     foo is still 10
300
301 Technical Note: the localisation of the stash (that is, the process by
302 which variables are copied before an C<INCLUDE> to prevent being
303 overwritten) is only skin deep.  The top-level variable namespace
304 (hash) is copied, but no attempt is made to perform a deep-copy of
305 other structures (hashes, arrays, objects, etc.)  Therefore, a C<foo>
306 variable referencing a hash will be copied to create a new C<foo>
307 variable but which points to the same hash array.  Thus, if you update
308 compound variables (e.g. C<foo.bar>) then you will change the original
309 copy, regardless of any stash localisation.  If you're not worried
310 about preserving variable values, or you trust the templates you're
311 including then you might prefer to use the C<PROCESS> directive which is
312 faster by virtue of not performing any localisation.
313
314 You can specify dotted variables as "local" variables to an C<INCLUDE> directive.
315 However, be aware that because of the localisation issues explained above (if
316 you skipped the previous Technical Note above then you might want to go back
317 and read it or skip this section too), the variables might not actualy be
318 "local". If the first element of the variable name already references a hash
319 array then the variable update will affect the original variable.
320
321     [% foo = {
322            bar = 'Baz'
323        }
324     %]
325     
326     [% INCLUDE somefile foo.bar='Boz' %]
327     
328     [% foo.bar %]           # Boz
329
330 This behaviour can be a little unpredictable (and may well be improved
331 upon in a future version).  If you know what you're doing with it and 
332 you're sure that the variables in question are defined (nor not) as you 
333 expect them to be, then you can rely on this feature to implement some
334 powerful "global" data sharing techniques.  Otherwise, you might prefer
335 to steer well clear and always pass simple (undotted) variables as 
336 parameters to C<INCLUDE> and other similar directives.
337
338 If you want to process several templates in one go then you can 
339 specify each of their names (quoted or unquoted names only, no unquoted
340 C<$variables>) joined together by C<+>.  The C<INCLUDE> directive
341 will then process them in order.
342
343     [% INCLUDE html/header + "site/$header" + site/menu
344          title = "My Groovy Web Site"
345     %]
346
347 The variable stash is localised once and then the templates specified
348 are processed in order, all within that same variable context.  This
349 makes it slightly faster than specifying several separate C<INCLUDE>
350 directives (because you only clone the variable stash once instead of
351 n times), but not quite as "safe" because any variable changes in the
352 first file will be visible in the second, third and so on.  This
353 might be what you want, of course, but then again, it might not.
354
355 =head2 PROCESS
356
357 The PROCESS directive is similar to C<INCLUDE> but does not perform any 
358 localisation of variables before processing the template.  Any changes
359 made to variables within the included template will be visible in the
360 including template.
361
362     [% foo = 10 %]
363     
364     foo is [% foo %]
365     [% PROCESS bar %]
366     foo is [% foo %]
367     
368     [% BLOCK bar %]
369        [% foo = 20 %]
370        changed foo to [% foo %]
371     [% END %]
372
373 output:
374
375     foo is 10
376        changed foo to 20
377     foo is 20
378
379 Parameters may be specified in the C<PROCESS> directive, but these too will 
380 become visible changes to current variable values.
381
382     [% foo = 10 %]
383     foo is [% foo %]
384     [% PROCESS bar
385        foo = 20 
386     %]
387     foo is [% foo %]
388     
389     [% BLOCK bar %]
390        this is bar, foo is [% foo %]
391     [% END %]
392
393 output:
394
395     foo is 10
396        this is bar, foo is 20
397     foo is 20
398
399 The C<PROCESS> directive is slightly faster than C<INCLUDE> because it
400 avoids the need to localise (i.e. copy) the variable stash before
401 processing the template.  As with C<INSERT> and C<INCLUDE>, the first
402 parameter does not need to be quoted as long as it contains only
403 alphanumeric characters, underscores, periods or forward slashes.
404 A C<$> prefix can be used to explicitly indicate a variable which 
405 should be interpolated to provide the template name:
406
407     [% myheader = 'my/misc/header' %]
408     [% PROCESS  myheader %]              # 'myheader'
409     [% PROCESS $myheader %]              # 'my/misc/header'
410
411 As with C<INCLUDE>, multiple templates can be specified, delimited by
412 C<+>, and are processed in order.
413
414     [% PROCESS html/header + my/header %]
415
416 =head2 WRAPPER
417
418 It's not unusual to find yourself adding common headers and footers to 
419 pages or sub-sections within a page.  Something like this:
420
421     [% INCLUDE section/header
422        title = 'Quantum Mechanics'
423     %]
424        Quantum mechanics is a very interesting subject wish 
425        should prove easy for the layman to fully comprehend.
426     [% INCLUDE section/footer %]
427     
428     [% INCLUDE section/header
429        title = 'Desktop Nuclear Fusion for under $50'
430     %]
431        This describes a simple device which generates significant 
432        sustainable electrical power from common tap water by process 
433        of nuclear fusion.
434     [% INCLUDE section/footer %]
435
436 The individual template components being included might look like these:
437
438 section/header:
439
440     <p>
441     <h2>[% title %]</h2>
442
443 section/footer:
444
445     </p>
446
447 The C<WRAPPER> directive provides a way of simplifying this a little. It
448 encloses a block up to a matching C<END> directive, which is first processed
449 to generate some output. This is then passed to the named template file or
450 C<BLOCK> as the C<content> variable.
451
452     [% WRAPPER section
453        title = 'Quantum Mechanics'
454     %]
455        Quantum mechanics is a very interesting subject wish 
456        should prove easy for the layman to fully comprehend.
457     [% END %]
458     
459     [% WRAPPER section
460        title = 'Desktop Nuclear Fusion for under $50'
461     %]
462        This describes a simple device which generates significant 
463        sustainable electrical power from common tap water by process 
464        of nuclear fusion.
465     [% END %]
466
467 The single 'section' template can then be defined as:
468
469     <h2>[% title %]</h2>
470     <p>
471       [% content %]
472     </p>
473
474 Like other block directives, it can be used in side-effect notation:
475
476     [% INSERT legalese.txt WRAPPER big_bold_table %]
477
478 It's also possible to specify multiple templates to a C<WRAPPER> directive.
479 The specification order indicates outermost to innermost wrapper templates.
480 For example, given the following template block definitions:
481
482     [% BLOCK bold   %]<b>[% content %]</b>[% END %]
483     [% BLOCK italic %]<i>[% content %]</i>[% END %]
484
485 the directive 
486
487     [% WRAPPER bold+italic %]Hello World[% END %]
488
489 would generate the following output:
490
491     <b><i>Hello World</i></b>
492
493 =head2 BLOCK
494
495 The C<BLOCK>...C<END> construct can be used to define template component
496 blocks which can be processed with the C<INCLUDE>, C<PROCESS> and C<WRAPPER>
497 directives.
498
499     [% BLOCK tabrow %]
500     <tr>
501       <td>[% name %]<td>
502       <td>[% email %]</td>
503     </tr>
504     [% END %]
505     
506     <table>
507       [% PROCESS tabrow  name='Fred'  email='fred@nowhere.com' %]
508       [% PROCESS tabrow  name='Alan'  email='alan@nowhere.com' %]
509     </table>
510
511 A C<BLOCK> definition can be used before it is defined, as long as the
512 definition resides in the same file.  The block definition itself does
513 not generate any output.
514
515     [% PROCESS tmpblk %]
516     
517     [% BLOCK tmpblk %] This is OK [% END %]
518
519 You can use an anonymous C<BLOCK> to capture the output of a template
520 fragment.  
521
522     [% julius = BLOCK %]
523        And Caesar's spirit, ranging for revenge,
524        With Ate by his side come hot from hell,
525        Shall in these confines with a monarch's voice
526        Cry  'Havoc', and let slip the dogs of war;
527        That this foul deed shall smell above the earth
528        With carrion men, groaning for burial.
529     [% END %]
530
531 Like a named block, it can contain any other template directives which 
532 are processed when the block is defined.  The output generated by the 
533 block is then assigned to the variable C<julius>.
534
535 Anonymous C<BLOCK>s can also be used to define block macros.  The
536 enclosing block is processed each time the macro is called.
537
538     [% MACRO locate BLOCK %]
539        The [% animal %] sat on the [% place %].
540     [% END %]
541     
542     [% locate(animal='cat', place='mat') %]    # The cat sat on the mat
543     [% locate(animal='dog', place='log') %]    # The dog sat on the log
544
545 =head1 Conditional Processing
546
547 =head2 IF / UNLESS / ELSIF / ELSE
548
549 The C<IF> and C<UNLESS> directives can be used to process or ignore a
550 block based on some run-time condition.  
551
552     [% IF frames %]
553        [% INCLUDE frameset %]
554     [% END %]
555     
556     [% UNLESS text_mode %]
557        [% INCLUDE biglogo %]
558     [% END %]
559
560 Multiple conditions may be joined with C<ELSIF> and/or C<ELSE> blocks.
561
562     [% IF age < 10 %]
563        Hello [% name %], does your mother know you're 
564        using her AOL account?
565     [% ELSIF age < 18 %]
566        Sorry, you're not old enough to enter 
567        (and too dumb to lie about your age)
568     [% ELSE %]
569        Welcome [% name %].
570     [% END %]
571
572 The following conditional and boolean operators may be used:
573
574     == != < <= > >= && || ! and or not
575
576 Conditions may be arbitrarily complex and are evaluated with the same
577 precedence as in Perl.  Parenthesis may be used to explicitly
578 determine evaluation order.
579
580     # ridiculously contrived complex example
581     [% IF (name == 'admin' || uid <= 0) && mode == 'debug' %]
582        I'm confused.
583     [% ELSIF more > less %]
584        That's more or less correct.
585     [% END %]
586
587 The C<and>, C<or> and C<not> operator are provided as aliases for
588 C<&&>, C<||> and C<!>, respectively.  Unlike Perl, which treats 
589 C<and>, C<or> and C<not> as separate, lower-precedence versions of the 
590 other operators, the Template Toolkit performs a straightforward substitution
591 of C<and> for C<&&>, and so on.  That means that C<and>, C<or> and C<not>
592 have the same operator precedence as C<&&>, C<||> and C<!>.
593
594 =head2 SWITCH / CASE
595
596 The C<SWITCH> / C<CASE> construct can be used to perform a multi-way
597 conditional test.  The C<SWITCH> directive expects an expression which is
598 first evaluated and then compared against each CASE statement in turn.
599 Each C<CASE> directive should contain a single value or a list of values
600 which should match.  C<CASE> may also be left blank or written as 
601 C<[% CASE DEFAULT %]> to specify a default match.  Only one C<CASE> matches,
602 there is no drop-through between C<CASE> statements.
603
604     [% SWITCH myvar %]
605     [%   CASE 'value1' %]
606            ...
607     [%   CASE ['value2', 'value3'] %]   # multiple values
608            ...
609     [%   CASE myhash.keys %]            # ditto
610            ...
611     [%   CASE %]                        # default
612            ...
613     [% END %]
614
615 =head1 Loop Processing
616
617 =head2 FOREACH
618
619 The C<FOREACH> directive will iterate through the items in a list, processing
620 the enclosed block for each one.
621
622     [% foo   = 'Foo'
623        items = [ 'one', 'two', 'three' ]
624     %]
625     
626     Things:
627     [% FOREACH thing IN [ foo 'Bar' "$foo Baz" ] %]
628        * [% thing %]
629     [% END %]
630     
631     Items:
632     [% FOREACH i IN items %]
633        * [% i %]
634     [% END %]
635     
636     Stuff:
637     [% stuff = [ foo "$foo Bar" ] %]
638     [% FOREACH s IN stuff %]
639        * [% s %]
640     [% END %]
641
642 output:
643
644     Things:
645       * Foo
646       * Bar
647       * Foo Baz
648     
649     Items:
650       * one
651       * two
652       * three
653     
654     Stuff:
655       * Foo
656       * Foo Bar
657
658 You can use also use C<=> instead of C<IN> if you prefer.
659
660     [% FOREACH i = items %]
661
662 When the C<FOREACH> directive is used without specifying a target variable, 
663 any iterated values which are hash references will be automatically 
664 imported.
665
666     [% userlist = [
667         { id => 'tom',   name => 'Thomas'  },
668         { id => 'dick',  name => 'Richard'  },
669         { id => 'larry', name => 'Lawrence' },
670        ]
671     %]
672     
673     [% FOREACH user IN userlist %]
674        [% user.id %] [% user.name %]
675     [% END %]
676
677 short form:
678
679     [% FOREACH userlist %]
680        [% id %] [% name %]
681     [% END %]
682
683 Note that this particular usage creates a localised variable context
684 to prevent the imported hash keys from overwriting any existing
685 variables.  The imported definitions and any other variables defined
686 in such a C<FOREACH> loop will be lost at the end of the loop, when the 
687 previous context and variable values are restored.
688
689 However, under normal operation, the loop variable remains in scope
690 after the C<FOREACH> loop has ended (caveat: overwriting any variable
691 previously in scope). This is useful as the loop variable is secretly
692 an iterator object (see below) and can be used to analyse the last
693 entry processed by the loop.
694
695 The C<FOREACH> directive can also be used to iterate through the entries
696 in a hash array.  Each entry in the hash is returned in sorted order
697 (based on the key) as a hash array containing 'key' and 'value' items.
698
699     [% users = {
700          tom   => 'Thomas',
701          dick  => 'Richard',
702          larry => 'Lawrence',
703        }
704     %]
705     
706     [% FOREACH u IN users %]
707        * [% u.key %] : [% u.value %]
708     [% END %]
709
710 Output:
711
712        * dick : Richard
713        * larry : Lawrence
714        * tom : Thomas      
715
716 The C<NEXT> directive starts the next iteration in the C<FOREACH> loop.
717
718     [% FOREACH user IN userlist %]
719        [% NEXT IF user.isguest %]
720        Name: [% user.name %]    Email: [% user.email %]
721     [% END %]
722
723 The C<LAST> directive can be used to prematurely exit the loop.  C<BREAK> is
724 also provided as an alias for C<LAST>.
725
726     [% FOREACH match IN results.nsort('score').reverse %]
727        [% LAST IF match.score < 50 %]
728        [% match.score %] : [% match.url %]
729     [% END %]
730
731 The C<FOREACH> directive is implemented using the L<Template::Iterator>
732 module.  A reference to the iterator object for a C<FOREACH> directive is
733 implicitly available in the C<loop> variable.  The following methods 
734 can be called on the C<loop> iterator.
735
736     size()      number of elements in the list
737     max()       index number of last element (size - 1)
738     index()     index of current iteration from 0 to max()
739     count()     iteration counter from 1 to size() (i.e. index() + 1)
740     first()     true if the current iteration is the first
741     last()      true if the current iteration is the last
742     prev()      return the previous item in the list
743     next()      return the next item in the list
744
745 See L<Template::Iterator> for further details.
746
747 Example:
748
749     [% FOREACH item IN [ 'foo', 'bar', 'baz' ] -%]
750        [%- "<ul>\n" IF loop.first %]
751        <li>[% loop.count %]/[% loop.size %]: [% item %]
752        [%- "</ul>\n" IF loop.last %]
753     [% END %]
754
755 Output:
756
757     <ul>
758     <li>1/3: foo
759     <li>2/3: bar
760     <li>3/3: baz
761     </ul>
762
763 Nested loops will work as expected, with the C<loop> variable correctly 
764 referencing the innermost loop and being restored to any previous 
765 value (i.e. an outer loop) at the end of the loop.
766
767     [% FOREACH group IN grouplist;
768          # loop => group iterator
769          "Groups:\n" IF loop.first;
770          
771          FOREACH user IN group.userlist;
772             # loop => user iterator
773             "$loop.count: $user.name\n";
774          END;
775          
776          # loop => group iterator
777          "End of Groups\n" IF loop.last;
778        END 
779     %]
780
781 The C<iterator> plugin can also be used to explicitly create an
782 iterator object.  This can be useful within nested loops where you
783 need to keep a reference to the outer iterator within the inner loop.
784 The iterator plugin effectively allows you to create an iterator by a
785 name other than C<loop>.  See L<Template::Plugin::Iterator> for further
786 details.
787
788     [% USE giter = iterator(grouplist) %]
789     
790     [% FOREACH group IN giter %]
791        [% FOREACH user IN group.userlist %]
792              user #[% loop.count %] in
793              group [% giter.count %] is
794              named [% user.name %]
795        [% END %]
796     [% END %]
797
798 =head2 WHILE
799
800 The C<WHILE> directive can be used to repeatedly process a template block
801 while a conditional expression evaluates true.  The expression may 
802 be arbitrarily complex as per C<IF> / C<UNLESS>.
803
804     [% WHILE total < 100 %]
805        ...
806        [% total = calculate_new_total %]
807     [% END %]
808
809 An assignment can be enclosed in parenthesis to evaluate the assigned
810 value.
811
812     [% WHILE (user = get_next_user_record) %]
813        [% user.name %]
814     [% END %]
815
816 The C<NEXT> directive can be used to start the next iteration of a 
817 C<WHILE> loop and C<BREAK> can be used to exit the loop, both as per C<FOREACH>.
818
819 The Template Toolkit uses a failsafe counter to prevent runaway C<WHILE>
820 loops which would otherwise never terminate.  If the loop exceeds 1000
821 iterations then an C<undef> exception will be thrown, reporting the
822 error:
823
824     WHILE loop terminated (> 1000 iterations)
825
826 The C<$Template::Directive::WHILE_MAX> variable controls this behaviour
827 and can be set to a higher value if necessary.
828
829 =head1 Filters, Plugins, Macros and Perl
830
831 =head2 FILTER
832
833 The C<FILTER> directive can be used to post-process the output of a
834 block.  A number of standard filters are provided with the Template
835 Toolkit.  The C<html> filter, for example, escapes the 'E<lt>', 'E<gt>'
836 and '&' characters to prevent them from being interpreted as HTML tags
837 or entity reference markers.
838
839     [% FILTER html %]
840        HTML text may have < and > characters embedded
841        which you want converted to the correct HTML entities.
842     [% END %]
843
844 output:
845
846        HTML text may have &lt; and &gt; characters embedded
847        which you want converted to the correct HTML entities.
848
849 The C<FILTER> directive can also follow various other non-block directives.
850 For example:
851
852     [% INCLUDE mytext FILTER html %]
853
854 The C<|> character can also be used as an alias for C<FILTER>.
855
856     [% INCLUDE mytext | html %]
857
858 Multiple filters can be chained together and will be called in sequence.
859
860     [% INCLUDE mytext FILTER html FILTER html_para %]
861
862 or
863
864     [% INCLUDE mytext | html | html_para %]
865
866 Filters come in two flavours, known as 'static' or 'dynamic'.  A
867 static filter is a simple subroutine which accepts a text string as
868 the only argument and returns the modified text.  The C<html> filter is
869 an example of a static filter, implemented as:
870
871     sub html_filter {
872         my $text = shift;
873         for ($text) {
874             s/&/&amp;/g;
875             s/</&lt;/g;
876             s/>/&gt;/g;
877         }
878         return $text;
879     }
880
881 Dynamic filters can accept arguments which are specified when the filter
882 is called from a template.  The C<repeat> filter is such an example, 
883 accepting a numerical argument which specifies the number of times
884 that the input text should be repeated.
885
886     [% FILTER repeat(3) %]blah [% END %]
887
888 output:
889
890     blah blah blah
891
892 These are implemented as filter 'factories'.  The factory subroutine
893 is passed a reference to the current L<Template::Context> object along
894 with any additional arguments specified.  It should then return a
895 subroutine reference (e.g. a closure) which implements the filter.
896 The C<repeat> filter factory is implemented like this:
897
898     sub repeat_filter_factory {
899         my ($context, $iter) = @_;
900         $iter = 1 unless defined $iter;
901         
902         return sub {
903             my $text = shift;
904             $text = '' unless defined $text;
905             return join('\n', $text) x $iter;
906         }
907     }
908
909 The C<FILTERS> option, described in L<Template::Manual::Config>, allows custom
910 filters to be defined when a Template object is instantiated. The
911 L<define_filter()|Template::Context#define_filter()> method allows further
912 filters to be defined at any time.
913
914 When using a filter, it is possible to assign an alias to it for 
915 further use.  This is most useful for dynamic filters that you want 
916 to re-use with the same configuration.
917
918     [% FILTER echo = repeat(2) %]
919     Is there anybody out there?
920     [% END %]
921     
922     [% FILTER echo %]
923     Mother, should I build a wall?
924     [% END %]
925
926 Output:
927
928     Is there anybody out there?
929     Is there anybody out there?
930
931     Mother, should I build a wall?
932     Mother, should I build a wall?
933
934 The C<FILTER> directive automatically quotes the name of the filter.  As
935 with C<INCLUDE> et al, you can use a variable to provide the name of the 
936 filter, prefixed by C<$>.
937
938     [% myfilter = 'html' %]
939     [% FILTER $myfilter %]      # same as [% FILTER html %]
940        ...
941     [% END %]
942
943 A template variable can also be used to define a static filter
944 subroutine.  However, the Template Toolkit will automatically call any
945 subroutine bound to a variable and use the value returned.  Thus, the
946 above example could be implemented as:
947
948     my $vars = {
949         myfilter => sub { return 'html' },
950     };
951
952 template:
953
954     [% FILTER $myfilter %]      # same as [% FILTER html %]
955        ...
956     [% END %]
957
958 To define a template variable that evaluates to a subroutine reference
959 that can be used by the C<FILTER> directive, you should create a
960 subroutine that, when called automatically by the Template Toolkit,
961 returns another subroutine reference which can then be used to perform
962 the filter operation.  Note that only static filters can be
963 implemented in this way.
964
965     my $vars = {
966         myfilter => sub { \&my_filter_sub },
967     };
968     
969     sub my_filter_sub {
970         my $text = shift;
971         # do something
972         return $text;
973     }
974
975 template:
976
977     [% FILTER $myfilter %]
978        ...
979     [% END %]
980
981 Alternately, you can bless a subroutine reference into a class (any
982 class will do) to fool the Template Toolkit into thinking it's an
983 object rather than a subroutine.  This will then bypass the automatic
984 "call-a-subroutine-to-return-a-value" magic.
985
986     my $vars = {
987         myfilter => bless(\&my_filter_sub, 'anything_you_like'),
988     };
989
990 template:
991
992     [% FILTER $myfilter %]          
993        ...
994     [% END %]
995
996 Filters bound to template variables remain local to the variable context in
997 which they are defined. That is, if you define a filter in a C<PERL> block
998 within a template that is loaded via C<INCLUDE>, then the filter definition
999 will only exist until the end of that template when the stash is delocalised,
1000 restoring the previous variable state. If you want to define a filter which
1001 persists for the lifetime of the processor, or define additional dynamic
1002 filter factories, then you can call the
1003 L<define_filter()|Template::Context#define_filter()> method on the current
1004 L<Template::Context> object.
1005
1006 See L<Template::Manual::Filters> for a complete list of available filters,
1007 their descriptions and examples of use.
1008
1009 =head2 USE
1010
1011 The C<USE> directive can be used to load and initialise "plugin"
1012 extension modules.
1013
1014     [% USE myplugin %]
1015
1016 A plugin is a regular Perl module that conforms to a particular
1017 object-oriented interface, allowing it to be loaded into and used
1018 automatically by the Template Toolkit.  For details of this interface
1019 and information on writing plugins, consult L<Template::Plugin>. 
1020
1021 A number of standard plugins are included with the Template Toolkit
1022 (see below and L<Template::Manual::Plugins>).  The names of these
1023 standard plugins are case insensitive.  
1024
1025     [% USE CGI   %]        # => Template::Plugin::CGI
1026     [% USE Cgi   %]        # => Template::Plugin::CGI
1027     [% USE cgi   %]        # => Template::Plugin::CGI
1028
1029 You can also define further plugins using the C<PLUGINS> option.  
1030
1031     my $tt = Template->new({
1032         PLUGINS => {
1033             foo => 'My::Plugin::Foo',
1034             bar => 'My::Plugin::Bar',
1035         },
1036     });
1037
1038 The recommended convention is to specify these plugin names in lower
1039 case.  The Template Toolkit first looks for an exact case-sensitive
1040 match and then tries the lower case conversion of the name specified.
1041
1042     [% USE Foo %]      # look for 'Foo' then 'foo'
1043
1044 If you define all your C<PLUGINS> with lower case names then they will be
1045 located regardless of how the user specifies the name in the C<USE>
1046 directive.  If, on the other hand, you define your C<PLUGINS> with upper
1047 or mixed case names then the name specified in the C<USE> directive must
1048 match the case exactly.  
1049
1050 If the plugin isn't defined in either the standard plugins
1051 (C<$Template::Plugins::STD_PLUGINS>) or via the C<PLUGINS> option, then 
1052 the C<PLUGIN_BASE> is searched.
1053
1054 In this case the plugin name I<is> case-sensitive.  It is appended to
1055 each of the C<PLUGIN_BASE> module namespaces in turn (default:
1056 C<Template::Plugin>) to construct a full module name which it attempts
1057 to locate and load.  Any periods, 'C<.>', in the name will be converted
1058 to 'C<::>'.
1059
1060     [% USE MyPlugin %]     #  => Template::Plugin::MyPlugin
1061     [% USE Foo.Bar  %]     #  => Template::Plugin::Foo::Bar
1062
1063 The C<LOAD_PERL> option (disabled by default) provides a further way by
1064 which external Perl modules may be loaded.  If a regular Perl module
1065 (i.e. not a C<Template::Plugin::*> or other module relative to some
1066 C<PLUGIN_BASE>) supports an object-oriented interface and a C<new()>
1067 constructor then it can be loaded and instantiated automatically.  The
1068 following trivial example shows how the IO::File module might be used.
1069
1070     [% USE file = IO.File('/tmp/mydata') %]
1071     
1072     [% WHILE (line = file.getline) %]
1073        <!-- [% line %] -->
1074     [% END %]
1075
1076 Any additional parameters supplied in parenthesis after the plugin
1077 name will be also be passed to the C<new()> constructor.  A reference to
1078 the current L<Template::Context> object is passed as the first
1079 parameter.
1080
1081     [% USE MyPlugin('foo', 123) %]
1082
1083 equivalent to:
1084
1085     Template::Plugin::MyPlugin->new($context, 'foo', 123);
1086
1087 The only exception to this is when a module is loaded via the
1088 C<LOAD_PERL> option.  In this case the C<$context> reference is I<not>
1089 passed to the C<new()> constructor.  This is based on the assumption that
1090 the module is a regular Perl module rather than a Template Toolkit
1091 plugin so isn't expecting a context reference and wouldn't know what
1092 to do with it anyway.
1093
1094 Named parameters may also be specified.  These are collated into a
1095 hash which is passed by reference as the last parameter to the
1096 constructor, as per the general code calling interface.
1097
1098     [% USE url('/cgi-bin/foo', mode='submit', debug=1) %]
1099
1100 equivalent to:
1101
1102     Template::Plugin::URL->new(
1103         $context, 
1104         '/cgi-bin/foo'
1105         { mode => 'submit', debug => 1 }
1106     );
1107
1108 The plugin may represent any data type; a simple variable, hash, list or
1109 code reference, but in the general case it will be an object reference.
1110 Methods can be called on the object (or the relevant members of the
1111 specific data type) in the usual way:
1112
1113     [% USE table(mydata, rows=3) %]
1114     
1115     [% FOREACH row IN table.rows %]
1116        <tr>    
1117        [% FOREACH item IN row %]
1118         <td>[% item %]</td>
1119        [% END %]
1120        </tr>
1121     [% END %]
1122
1123 An alternative name may be provided for the plugin by which it can be 
1124 referenced:
1125
1126     [% USE scores = table(myscores, cols=5) %]
1127     
1128     [% FOREACH row IN scores.rows %]
1129        ...
1130     [% END %]
1131
1132 You can use this approach to create multiple plugin objects with
1133 different configurations.  This example shows how the 
1134 L<format|Template::Plugin::Format> plugin is used to create 
1135 sub-routines bound to variables for formatting text as per C<printf()>.
1136
1137     [% USE bold = format('<b>%s</b>') %]
1138     [% USE ital = format('<i>%s</i>') %]
1139     [% bold('This is bold')   %]
1140     [% ital('This is italic') %]
1141
1142 Output:
1143
1144     <b>This is bold</b>
1145     <i>This is italic</i>
1146
1147 This next example shows how the L<URL|Template::Plugin::URL> plugin can be
1148 used to build dynamic URLs from a base part and optional query parameters.
1149
1150     [% USE mycgi = URL('/cgi-bin/foo.pl', debug=1) %]
1151     <a href="[% mycgi %]">...
1152     <a href="[% mycgi(mode='submit') %]"...
1153
1154 Output:
1155
1156     <a href="/cgi-bin/foo.pl?debug=1">...
1157     <a href="/cgi-bin/foo.pl?mode=submit&debug=1">...
1158
1159 The L<CGI|Template::Plugin::CGI> plugin is an example of one which delegates
1160 to another Perl module. In this this case, to Lincoln Stein's C<CGI> module.
1161 All of the methods provided by the C<CGI> module are available via the plugin.
1162
1163     [% USE CGI;
1164        CGI.start_form;
1165        CGI.checkbox_group( name   = 'colours', 
1166                            values = [ 'red' 'green' 'blue' ] );
1167        CGI.popup_menu( name   = 'items', 
1168                        values = [ 'foo' 'bar' 'baz' ] );
1169        CGI.end_form 
1170     %]
1171
1172 See L<Template::Manual::Plugins> for more information on the plugins
1173 distributed with the toolkit or available from CPAN.
1174
1175 =head2 MACRO
1176
1177 The C<MACRO> directive allows you to define a directive or directive block
1178 which is then evaluated each time the macro is called. 
1179
1180     [% MACRO header INCLUDE header %]
1181
1182 Calling the macro as:
1183
1184     [% header %]
1185
1186 is then equivalent to:
1187
1188     [% INCLUDE header %]
1189
1190 Macros can be passed named parameters when called.  These values remain 
1191 local to the macro.
1192
1193     [% header(title='Hello World') %]  
1194
1195 equivalent to:
1196
1197     [% INCLUDE header title='Hello World' %]
1198
1199 A C<MACRO> definition may include parameter names.  Values passed to the 
1200 macros are then mapped to these local variables.  Other named parameters
1201 may follow these.
1202
1203     [% MACRO header(title) INCLUDE header %]
1204     [% header('Hello World') %]
1205     [% header('Hello World', bgcol='#123456') %]
1206
1207 equivalent to:
1208
1209     [% INCLUDE header title='Hello World' %]
1210     [% INCLUDE header title='Hello World' bgcol='#123456' %]
1211
1212 Here's another example, defining a macro for display numbers
1213 in comma-delimited groups of 3, using the chunk and join virtual
1214 method.
1215
1216     [% MACRO number(n) GET n.chunk(-3).join(',') %]
1217     [% number(1234567) %]    # 1,234,567
1218
1219 A C<MACRO> may precede any directive and must conform to the structure 
1220 of the directive.
1221
1222     [% MACRO header IF frames %]
1223        [% INCLUDE frames/header %]
1224     [% ELSE %]
1225        [% INCLUDE header %]
1226     [% END %]
1227     
1228     [% header %]
1229
1230 A C<MACRO> may also be defined as an anonymous C<BLOCK>.  The block will be
1231 evaluated each time the macro is called. 
1232
1233     [% MACRO header BLOCK %]
1234        ...content...
1235     [% END %]
1236     
1237     [% header %]
1238
1239 If you've got the C<EVAL_PERL> option set, then you can even define a
1240 C<MACRO> as a C<PERL> block (see below):
1241
1242     [% MACRO triple(n) PERL %]
1243          my $n = $stash->get('n');
1244          print $n * 3;
1245     [% END -%]
1246
1247 =head2 PERL
1248
1249 (for the advanced reader)
1250
1251 The C<PERL> directive is used to mark the start of a block which contains
1252 Perl code for evaluation.  The C<EVAL_PERL> option must be enabled for Perl
1253 code to be evaluated or a C<perl> exception will be thrown with the 
1254 message 'C<EVAL_PERL not set>'.
1255
1256 Perl code is evaluated in the C<Template::Perl> package.  The C<$context>
1257 package variable contains a reference to the current L<Template::Context>
1258 object.  This can be used to access the functionality of the Template
1259 Toolkit to process other templates, load plugins, filters, etc.
1260 See L<Template::Context> for further details.
1261
1262     [% PERL %]
1263        print $context->include('myfile');
1264     [% END %]
1265
1266 The L<$stash> variable contains a reference to the top-level stash object
1267 which manages template variables.  Through this, variable values can
1268 be retrieved and updated.  See L<Template::Stash> for further details.
1269
1270     [% PERL %]
1271        $stash->set(foo => 'bar');
1272        print "foo value: ", $stash->get('foo');
1273     [% END %]
1274
1275 Output:
1276
1277     foo value: bar
1278
1279 Output is generated from the C<PERL> block by calling C<print()>.  Note that
1280 the C<Template::Perl::PERLOUT> handle is selected (tied to an output
1281 buffer) instead of C<STDOUT>.
1282
1283     [% PERL %]
1284        print "foo\n";                           # OK
1285        print PERLOUT "bar\n";                   # OK, same as above
1286        print Template::Perl::PERLOUT "baz\n";   # OK, same as above
1287        print STDOUT "qux\n";                    # WRONG!
1288     [% END %]
1289
1290 The C<PERL> block may contain other template directives.  These are
1291 processed before the Perl code is evaluated.
1292
1293     [% name = 'Fred Smith' %]
1294     
1295     [% PERL %]
1296        print "[% name %]\n";
1297     [% END %]
1298
1299 Thus, the Perl code in the above example is evaluated as:
1300
1301     print "Fred Smith\n";
1302
1303 Exceptions may be thrown from within C<PERL> blocks using C<die()>.
1304 They will be correctly caught by enclosing C<TRY> blocks.
1305
1306     [% TRY %]
1307        [% PERL %]
1308           die "nothing to live for\n";
1309        [% END %]
1310     [% CATCH %]
1311        error: [% error.info %]
1312     [% END %]
1313
1314 output:
1315        error: nothing to live for
1316
1317 =head2 RAWPERL
1318
1319 (for the very advanced reader)
1320
1321 The Template Toolkit parser reads a source template and generates the
1322 text of a Perl subroutine as output.  It then uses C<eval()> to evaluate
1323 it into a subroutine reference.  This subroutine is then called to
1324 process the template, passing a reference to the current
1325 L<Template::Context> object through which the functionality of the
1326 Template Toolkit can be accessed.  The subroutine reference can be
1327 cached, allowing the template to be processed repeatedly without
1328 requiring any further parsing.
1329
1330 For example, a template such as:
1331
1332     [% PROCESS header %]
1333     The [% animal %] sat on the [% location %]
1334     [% PROCESS footer %]
1335
1336 is converted into the following Perl subroutine definition:
1337
1338     sub {
1339         my $context = shift;
1340         my $stash   = $context->stash;
1341         my $output  = '';
1342         my $error;
1343         
1344         eval { BLOCK: {
1345             $output .=  $context->process('header');
1346             $output .=  "The ";
1347             $output .=  $stash->get('animal');
1348             $output .=  " sat on the ";
1349             $output .=  $stash->get('location');
1350             $output .=  $context->process('footer');
1351             $output .=  "\n";
1352         } };
1353         if ($@) {
1354             $error = $context->catch($@, \$output);
1355             die $error unless $error->type eq 'return';
1356         }
1357     
1358         return $output;
1359     }
1360
1361 To examine the Perl code generated, such as in the above example, set
1362 the C<$Template::Parser::DEBUG> package variable to any true value.  You
1363 can also set the C<$Template::Directive::PRETTY> variable true to have
1364 the code formatted in a readable manner for human consumption.  The
1365 source code for each generated template subroutine will be printed to
1366 C<STDERR> on compilation (i.e. the first time a template is used).
1367
1368     $Template::Parser::DEBUG = 1;
1369     $Template::Directive::PRETTY = 1;
1370     
1371     $template->process($file, $vars)
1372         || die $template->error(), "\n";
1373
1374 The C<PERL> ... C<END> construct allows Perl code to be embedded into a
1375 template when the C<EVAL_PERL> option is set.  It is evaluated at
1376 "runtime" using C<eval()> each time the template subroutine is called.
1377 This is inherently flexible, but not as efficient as it could be,
1378 especially in a persistent server environment where a template may be
1379 processed many times.  
1380
1381 The C<RAWPERL> directive allows you to write Perl code that is integrated
1382 directly into the generated Perl subroutine text.  It is evaluated
1383 once at compile time and is stored in cached form as part of the
1384 compiled template subroutine.  This makes C<RAWPERL> blocks more
1385 efficient than C<PERL> blocks.
1386
1387 The downside is that you must code much closer to the metal. For example, in a
1388 C<PERL> block you can call L<print()> to generate some output. C<RAWPERL>
1389 blocks don't afford such luxury. The code is inserted directly into the
1390 generated subroutine text and should conform to the convention of appending to
1391 the C<$output> variable.
1392
1393     [% PROCESS  header %]
1394     
1395     [% RAWPERL %]
1396        $output .= "Some output\n";
1397        ...
1398        $output .= "Some more output\n";
1399     [% END %]
1400
1401 The critical section of the generated subroutine for this example would 
1402 then look something like:
1403
1404     ...
1405     eval { BLOCK: {
1406         $output .=  $context->process('header');
1407         $output .=  "\n";
1408         $output .= "Some output\n";
1409         ...
1410         $output .= "Some more output\n";
1411         $output .=  "\n";
1412     } };
1413     ...
1414
1415 As with C<PERL> blocks, the L<$context|Template::Context> and
1416 L<$stash|Template::Stash> references are pre-defined and available for use
1417 within C<RAWPERL> code.
1418
1419 =head1 Exception Handling and Flow Control
1420
1421 =head2 TRY / THROW / CATCH / FINAL
1422
1423 (more advanced material)
1424
1425 The Template Toolkit supports fully functional, nested exception
1426 handling.  The C<TRY> directive introduces an exception handling scope 
1427 which continues until the matching C<END> directive.  Any errors that 
1428 occur within that block will be caught and can be handled by one
1429 of the C<CATCH> blocks defined.
1430
1431     [% TRY %]
1432        ...blah...blah...
1433        [% CALL somecode %]
1434        ...etc...
1435        [% INCLUDE someblock %]
1436        ...and so on...
1437     [% CATCH %]
1438        An error occurred!
1439     [% END %]
1440
1441 Errors are raised as exceptions (objects of the L<Template::Exception> class)
1442 which contain two fields: C<type> and C<info>. The exception C<type> is used
1443 to indicate the kind of error that occurred. It is a simple text string which
1444 can contain letters, numbers, 'C<_>' or 'C<.>'. The C<info> field contains an
1445 error message indicating what actually went wrong. Within a catch block, the
1446 exception object is aliased to the C<error> variable. You can access the C<type>
1447 and C<info> fields directly.
1448
1449     [% mydsn = 'dbi:MySQL:foobar' %]
1450     ...
1451     
1452     [% TRY %]
1453        [% USE DBI(mydsn) %]
1454     [% CATCH %]
1455        ERROR! Type: [% error.type %]
1456               Info: [% error.info %]
1457     [% END %]
1458
1459 output (assuming a non-existant database called 'C<foobar>'):
1460
1461     ERROR!  Type: DBI
1462             Info: Unknown database "foobar"
1463
1464 The C<error> variable can also be specified by itself and will return a 
1465 string of the form "C<$type error - $info>".
1466
1467     ...
1468     [% CATCH %]
1469     ERROR: [% error %]
1470     [% END %]
1471
1472 Output:
1473
1474     ERROR: DBI error - Unknown database "foobar"
1475
1476 Each C<CATCH> block may be specified with a particular exception type
1477 denoting the kind of error that it should catch.  Multiple C<CATCH>
1478 blocks can be provided to handle different types of exception that may
1479 be thrown in the C<TRY> block.  A C<CATCH> block specified without any type,
1480 as in the previous example, is a default handler which will catch any
1481 otherwise uncaught exceptions.  This can also be specified as 
1482 C<[% CATCH DEFAULT %]>.
1483
1484     [% TRY %]
1485        [% INCLUDE myfile %]
1486        [% USE DBI(mydsn) %]
1487        [% CALL somecode %]
1488     [% CATCH file %]
1489        File Error! [% error.info %]
1490     [% CATCH DBI %]
1491        [% INCLUDE database/error.html %]
1492     [% CATCH %]
1493        [% error %]
1494     [% END %]
1495
1496 Remember that you can specify multiple directives within a single tag,
1497 each delimited by 'C<;>'.  So the above example can be written more
1498 concisely as:
1499
1500     [% TRY;
1501            INCLUDE myfile;
1502            USE DBI(mydsn);
1503            CALL somecode;
1504        CATCH file;
1505            "File Error! $error.info";
1506        CATCH DBI;
1507            INCLUDE database/error.html;
1508        CATCH;
1509            error;
1510        END 
1511     %]
1512
1513 The C<DBI> plugin throws exceptions of the C<DBI> type (in case that
1514 wasn't already obvious).  The other specific exception caught here is
1515 of the C<file> type.
1516
1517 A C<file> exception is automatically thrown by the Template Toolkit when it
1518 can't find a file, or fails to load, parse or process a file that has been
1519 requested by an C<INCLUDE>, C<PROCESS>, C<INSERT> or C<WRAPPER> directive. 
1520 If C<myfile> can't be found in the example above, the C<[% INCLUDE myfile %]>
1521 directive will raise a C<file> exception which is then caught by the 
1522 C<[% CATCH file %]> block.  The output generated would be:
1523
1524     File Error! myfile: not found
1525
1526 Note that the C<DEFAULT> option (disabled by default) allows you to specify a
1527 default file to be used any time a template file can't be found. This will
1528 prevent file exceptions from ever being raised when a non-existant file is
1529 requested (unless, of course, the C<DEFAULT> file your specify doesn't exist).
1530 Errors encountered once the file has been found (i.e. read error, parse error)
1531 will be raised as file exceptions as per usual.
1532
1533 Uncaught exceptions (i.e. if the C<TRY> block doesn't have a type specific or
1534 default C<CATCH> handler) may be caught by enclosing C<TRY> blocks which can
1535 be nested indefinitely across multiple templates. If the error isn't caught at
1536 any level then processing will stop and the Template
1537 L<process()|Template#process()> method will return a false value to the
1538 caller. The relevant L<Template::Exception> object can be retrieved by calling
1539 the L<error()|Template#error()> method.
1540
1541     [% TRY %]
1542        ...
1543        [% TRY %]
1544           [% INCLUDE $user.header %]
1545        [% CATCH file %]
1546           [% INCLUDE header %]
1547        [% END %]
1548        ...
1549     [% CATCH DBI %]
1550        [% INCLUDE database/error.html %]
1551     [% END %]
1552
1553 In this example, the inner C<TRY> block is used to ensure that the first
1554 C<INCLUDE> directive works as expected.  We're using a variable to
1555 provide the name of the template we want to include, C<user.header>, and
1556 it's possible this contains the name of a non-existant template, or
1557 perhaps one containing invalid template directives.  If the C<INCLUDE> fails
1558 with a C<file> error then we C<CATCH> it in the inner block and C<INCLUDE>
1559 the default C<header> file instead.  Any C<DBI> errors that occur within
1560 the scope of the outer C<TRY> block will be caught in the relevant C<CATCH>
1561 block, causing the C<database/error.html> template to be processed.
1562 Note that included templates inherit all currently defined template
1563 variable so these error files can quite happily access the <error>
1564 variable to retrieve information about the currently caught exception.
1565 For example, the C<database/error.html> template might look like this:
1566
1567     <h2>Database Error</h2>
1568     A database error has occurred: [% error.info %]
1569
1570 You can also specify a C<FINAL> block.  This is always processed
1571 regardless of the outcome of the C<TRY> and/or C<CATCH> blocks.  If an
1572 exception is uncaught then the C<FINAL> block is processed before jumping
1573 to the enclosing block or returning to the caller.
1574
1575     [% TRY %]
1576        ...
1577     [% CATCH this %] 
1578        ...
1579     [% CATCH that %] 
1580        ...
1581     [% FINAL %]
1582        All done!
1583     [% END %]
1584
1585 The output from the C<TRY> block is left intact up to the point where an
1586 exception occurs.  For example, this template:
1587
1588     [% TRY %]
1589        This gets printed 
1590        [% THROW food 'carrots' %]
1591        This doesn't
1592     [% CATCH food %]
1593        culinary delights: [% error.info %]
1594     [% END %]    
1595
1596 generates the following output:
1597
1598     This gets printed
1599     culinary delights: carrots
1600
1601 The C<CLEAR> directive can be used in a C<CATCH> or C<FINAL> block to clear
1602 any output created in the C<TRY> block.
1603
1604     [% TRY %]
1605        This gets printed 
1606        [% THROW food 'carrots' %]
1607        This doesn't
1608     [% CATCH food %]
1609        [% CLEAR %]
1610        culinary delights: [% error.info %]
1611     [% END %]    
1612
1613 Output:
1614
1615     culinary delights: carrots
1616
1617 Exception types are hierarchical, with each level being separated by
1618 the familiar dot operator.  A C<DBI.connect> exception is a more
1619 specific kind of C<DBI> error.  Similarly, an C<example.error.barf> is a
1620 more specific kind of C<example.error> type which itself is also a
1621 C<example> error.  
1622
1623 A C<CATCH> handler that specifies a general exception
1624 type (such as C<DBI> or C<example.error>) will also catch more specific
1625 types that have the same prefix as long as a more specific handler
1626 isn't defined.  Note that the order in which C<CATCH> handlers are
1627 defined is irrelevant; a more specific handler will always catch an
1628 exception in preference to a more generic or default one.
1629
1630     [% TRY %]
1631        ...
1632     [% CATCH DBI ;
1633          INCLUDE database/error.html ;
1634        CATCH DBI.connect ;
1635          INCLUDE database/connect.html ;
1636        CATCH ; 
1637          INCLUDE error.html ;
1638        END
1639     %]
1640
1641 In this example, a C<DBI.connect> error has it's own handler, a more general
1642 C<DBI> block is used for all other C<DBI> or C<DBI.*> errors and a default
1643 handler catches everything else.
1644
1645 Exceptions can be raised in a template using the C<THROW> directive.  The
1646 first parameter is the exception type which doesn't need to be quoted
1647 (but can be, it's the same as C<INCLUDE>) followed by the relevant error
1648 message which can be any regular value such as a quoted string,
1649 variable, etc.
1650
1651     [% THROW food "Missing ingredients: $recipe.error" %]
1652     [% THROW user.login 'no user id: please login' %]
1653     [% THROW $myerror.type "My Error: $myerror.info" %]
1654
1655 It's also possible to specify additional positional or named 
1656 parameters to the C<THROW> directive if you want to pass more than 
1657 just a simple message back as the error info field.  
1658
1659     [% THROW food 'eggs' 'flour' msg='Missing Ingredients' %]
1660
1661 In this case, the error C<info> field will be a hash array containing the
1662 named arguments and an C<args> item which contains a list of the positional
1663 arguments.
1664
1665     type => 'food',
1666     info => {
1667         msg  => 'Missing Ingredients',
1668         args => ['eggs', 'flour'],
1669     }
1670
1671 In addition to specifying individual positional arguments as
1672 C<[% error.info.args.n %]>, the C<info> hash contains keys directly 
1673 pointing to the positional arguments, as a convenient shortcut.
1674
1675     [% error.info.0 %]   # same as [% error.info.args.0 %]
1676
1677 Exceptions can also be thrown from Perl code which you've bound to
1678 template variables, or defined as a plugin or other extension.  To
1679 raise an exception, call C<die()> passing a reference to a
1680 L<Template::Exception> object as the argument.  This will then be caught
1681 by any enclosing C<TRY> blocks from where the code was called.
1682
1683     use Template::Exception;
1684     ...
1685     my $vars = {
1686         foo => sub {
1687             # ... do something ...
1688             die Template::Exception->new('myerr.naughty',
1689                                          'Bad, bad error');
1690         },
1691     };
1692
1693 Template:
1694
1695     [% TRY %]
1696        [% foo %]
1697     [% CATCH myerr ;
1698          "Error: $error" ;
1699        END
1700     %]
1701
1702 Output:
1703
1704     Error: myerr.naughty error - Bad, bad error
1705
1706 The C<info> field can also be a reference to another object or data
1707 structure, if required.
1708
1709     die Template::Exception->new('myerror', { 
1710         module => 'foo.pl', 
1711         errors => [ 'bad permissions', 'naughty boy' ],
1712     });
1713
1714 Later, in a template:
1715
1716     [% TRY %]
1717        ...
1718     [% CATCH myerror %]
1719        [% error.info.errors.size or 'no';
1720           error.info.errors.size == 1 ? ' error' : ' errors' %]
1721        in [% error.info.module %]: 
1722           [% error.info.errors.join(', ') %].
1723     [% END %]
1724
1725 Generating the output:
1726
1727        2 errors in foo.pl:
1728           bad permissions, naughty boy.
1729
1730 You can also call C<die()> with a single string, as is common in much 
1731 existing Perl code.  This will automatically be converted to an 
1732 exception of the 'C<undef>' type (that's the literal string 'C<undef>', 
1733 not the undefined value).  If the string isn't terminated with a 
1734 newline then Perl will append the familiar C<" at $file line $line">
1735 message.
1736
1737     sub foo {
1738         # ... do something ...
1739         die "I'm sorry, Dave, I can't do that\n";
1740     }
1741
1742 If you're writing a plugin, or some extension code that has the current
1743 L<Template::Context> in scope (you can safely skip this section if this means
1744 nothing to you) then you can also raise an exception by calling the context
1745 L<throw()|Template::Context#throw()> method. You can pass it an
1746 L<Template::Exception> object reference, a pair of C<($type, $info)>
1747 parameters or just an C<$info> string to create an exception of 'C<undef>' type.
1748
1749     $context->throw($e);            # exception object
1750     $context->throw('Denied');      # 'undef' type
1751     $context->throw('user.passwd', 'Bad Password');
1752
1753 =head2 NEXT
1754
1755 The C<NEXT> directive can be used to start the next iteration of a C<FOREACH> 
1756 or C<WHILE> loop.
1757
1758     [% FOREACH user IN users %]
1759        [% NEXT IF user.isguest %]
1760        Name: [% user.name %]    Email: [% user.email %]
1761     [% END %]
1762
1763 =head2 LAST
1764
1765 The C<LAST> directive can be used to prematurely exit a C<FOREACH> or C<WHILE>
1766 loop.
1767
1768     [% FOREACH user IN users %]
1769        Name: [% user.name %]    Email: [% user.email %]
1770        [% LAST IF some.condition %]
1771     [% END %]
1772
1773 C<BREAK> can also be used as an alias for C<LAST>.
1774
1775 =head2 RETURN
1776
1777 The C<RETURN> directive can be used to stop processing the current template
1778 and return to the template from which it was called, resuming processing at
1779 the point immediately after the C<INCLUDE>, C<PROCESS> or C<WRAPPER>
1780 directive. If there is no enclosing template then the Template
1781 L<process()|Template#process()> method will return to the calling code with a
1782 true value.
1783
1784     Before
1785     [% INCLUDE half_wit %]
1786     After
1787     
1788     [% BLOCK half_wit %]
1789     This is just half...
1790     [% RETURN %]
1791     ...a complete block
1792     [% END %]
1793
1794 Output:
1795
1796     Before
1797     This is just half...
1798     After
1799
1800 =head2 STOP
1801
1802 The C<STOP> directive can be used to indicate that the processor should stop
1803 gracefully without processing any more of the template document. This is a
1804 planned stop and the Template L<process()|Template#process()> method will
1805 return a B<true> value to the caller. This indicates that the template was
1806 processed successfully according to the directives within it.
1807
1808     [% IF something.terrible.happened %]
1809        [% INCLUDE fatal/error.html %]
1810        [% STOP %]
1811     [% END %]
1812     
1813     [% TRY %]
1814        [% USE DBI(mydsn) %]
1815        ...
1816     [% CATCH DBI.connect %]
1817        <h1>Cannot connect to the database: [% error.info %]</h1>
1818        <p>
1819          We apologise for the inconvenience.
1820        </p>
1821        [% INCLUDE footer %]
1822        [% STOP %]
1823     [% END %]
1824
1825 =head2 CLEAR
1826
1827 The C<CLEAR> directive can be used to clear the output buffer for the current
1828 enclosing block.   It is most commonly used to clear the output generated
1829 from a C<TRY> block up to the point where the error occurred.
1830
1831     [% TRY %]
1832        blah blah blah            # this is normally left intact
1833        [% THROW some 'error' %]  # up to the point of error
1834        ...
1835     [% CATCH %]
1836        [% CLEAR %]               # clear the TRY output
1837        [% error %]               # print error string
1838     [% END %]
1839
1840 =head1 Miscellaneous
1841
1842 =head2 META
1843
1844 The C<META> directive allows simple metadata items to be defined within a
1845 template. These are evaluated when the template is parsed and as such may only
1846 contain simple values (e.g. it's not possible to interpolate other variables
1847 values into C<META> variables).
1848
1849     [% META
1850        title   = 'The Cat in the Hat'
1851        author  = 'Dr. Seuss'
1852        version = 1.23 
1853     %]
1854
1855 The C<template> variable contains a reference to the main template 
1856 being processed.  These metadata items may be retrieved as attributes
1857 of the template.  
1858
1859     <h1>[% template.title %]</h1>
1860     <h2>[% template.author %]</h2>
1861
1862 The C<name> and C<modtime> metadata items are automatically defined for each
1863 template to contain its name and modification time in seconds since the epoch.
1864
1865     [% USE date %]              # use Date plugin to format time
1866     ...
1867     [% template.name %] last modified
1868     at [% date.format(template.modtime) %]
1869
1870 The C<PRE_PROCESS> and C<POST_PROCESS> options allow common headers and 
1871 footers to be added to all templates.  The C<template> reference is
1872 correctly defined when these templates are processed, allowing headers
1873 and footers to reference metadata items from the main template.
1874
1875     $template = Template->new({
1876         PRE_PROCESS  => 'header',
1877         POST_PROCESS => 'footer',
1878     });
1879     
1880     $template->process('cat_in_hat');
1881
1882 header:
1883
1884     <html>
1885       <head>
1886         <title>[% template.title %]</title>
1887       </head>
1888       <body>
1889
1890 cat_in_hat:
1891
1892     [% META
1893          title   = 'The Cat in the Hat'
1894          author  = 'Dr. Seuss'
1895          version = 1.23 
1896          year    = 2000
1897     %]
1898     
1899         The cat in the hat sat on the mat.
1900
1901 footer:
1902
1903         <hr>
1904         &copy; [% template.year %] [% template.author %]
1905       </body>
1906     </html>
1907
1908 The output generated from the above example is:
1909
1910     <html>
1911       <head>
1912         <title>The Cat in the Hat</title>
1913       </head>
1914       <body>
1915         The cat in the hat sat on the mat.
1916         <hr>
1917         &copy; 2000 Dr. Seuss
1918       </body>
1919     </html>
1920
1921 =head2 TAGS
1922
1923 The C<TAGS> directive can be used to set the C<START_TAG> and C<END_TAG> values
1924 on a per-template file basis.
1925
1926     [% TAGS <+ +> %]
1927     
1928     <+ INCLUDE header +>
1929
1930 The TAGS directive may also be used to set a named C<TAG_STYLE>
1931
1932     [% TAGS html %]
1933     <!-- INCLUDE header -->
1934
1935 See the L<TAGS|Template::Manual::Config#TAGS> and L<TAG_STYLE|Template::Manual::Config#TAG_STYLE> 
1936 configuration options for further details.
1937
1938 =head2 DEBUG
1939
1940 The C<DEBUG> directive can be used to enable or disable directive debug
1941 messages within a template.  The C<DEBUG> configuration option must be
1942 set to include C<DEBUG_DIRS> for the C<DEBUG> directives to have any effect.
1943 If C<DEBUG_DIRS> is not set then the parser will automatically ignore and
1944 remove any C<DEBUG> directives.
1945
1946 The C<DEBUG> directive can be used with an C<on> or C<off> parameter to
1947 enable or disable directive debugging messages from that point
1948 forward.  When enabled, the output of each directive in the generated
1949 output will be prefixed by a comment indicate the file, line and
1950 original directive text.
1951
1952     [% DEBUG on %]
1953     directive debugging is on (assuming DEBUG option is set true)
1954     [% DEBUG off %]
1955     directive debugging is off
1956
1957 The C<format> parameter can be used to change the format of the debugging
1958 message.
1959
1960     [% DEBUG format '<!-- $file line $line : [% $text %] -->' %]
1961
1962 =cut
1963
1964 # Local Variables:
1965 # mode: perl
1966 # perl-indent-level: 4
1967 # indent-tabs-mode: nil
1968 # End:
1969 #
1970 # vim: expandtab shiftwidth=4: