]> Dogcows Code - chaz/p5-CGI-Ex/blob - lib/CGI/Ex/Template.pod
206dcba50de481df56efca3a6b77f2b064406ca2
[chaz/p5-CGI-Ex] / lib / CGI / Ex / Template.pod
1 =head1 NAME
2
3 CGI::Ex::Template - Fast and lightweight TT2/3 template engine
4
5 =head1 SYNOPSIS
6
7 my $t = CGI::Ex::Template->new(
8 INCLUDE_PATH => ['/path/to/templates'],
9 );
10
11 my $swap = {
12 key1 => 'val1',
13 key2 => 'val2',
14 code => sub { 42 },
15 hash => {a => 'b'},
16 };
17
18 # print to STDOUT
19 $t->process('my/template.tt', $swap)
20 || die $t->error;
21
22 # process into a variable
23 my $out = '';
24 $t->process('my/template.tt', $swap, \$out);
25
26 ### CET uses the same syntax and configuration as Template::Toolkit
27
28 =head1 DESCRIPTION
29
30 CGI::Ex::Template happened by accident (accidentally on purpose). The
31 CGI::Ex::Template (CET hereafter) was originally a part of the CGI::Ex
32 suite that performed simple variable interpolation. It used TT2 style
33 variables in TT2 style tags "[% foo.bar %]". That was all the
34 original CGI::Ex::Template did. This was fine and dandy for a couple
35 of years. In winter of 2005-2006 CET was revamped to add a few
36 features. One thing led to another and soon CET provided for most of
37 the features of TT2 as well as some from TT3. CGI::Ex::Template is a
38 full-featured implementation of the Template::Toolkit language.
39
40 CGI::Ex::Template (CET hereafter) is smaller, faster, uses less memory
41 and less CPU than TT2. However, it is most likely less portable, less
42 extendable, and probably has many of the bugs that TT2 has already massaged
43 out from years of bug reports and patches from a very active community
44 and mailing list. CET does not have a vibrant community behind it. Fixes
45 applied to TT2 will take longer to get into CET, should they get in at all.
46 An attempt will be made to follow updates made to TT2 to keep the two
47 in sync at a language level. There already has been, and it is expected that
48 there will continue to be code sharing between the two projects. (Acutally
49 I will try and keep applicable fixes in sync with TT).
50
51 CGI::Ex::Template uses a recursive regex based grammar (early versions
52 before the 2.10 release did not). This allows for the embedding of opening
53 and closing tags inside other tags (as in [% a = "[% 1 + 2 %]" ; a|eval %]).
54 The individual methods such as parse_expr and play_expr may be used by external
55 applications to add TT style variable parsing to other applications.
56
57 Most of the standard Template::Toolkit documentation covering directives,
58 variables, configuration, plugins, filters, syntax, and vmethods should
59 apply to CET just fine (This pod tries to explain everything - but there is
60 too much). The section on differences between CET and TT will explain
61 what too look out for.
62
63 Note: A clarification on "faster". All templates are going to take
64 different amounts of time to process. Different types of DIRECTIVES
65 parse and play more quickly than others. The test script
66 samples/benchmark/bench_template.pl was used to obtain sample numbers.
67 In general the following statements are true:
68
69 If you load a new Template object each time and pass a filename, CET
70 is around 3.5 times faster.
71
72 If you load a new Template object and pass a string ref, CET
73 is around 3 times faster.
74
75 If you load a new Template object and use CACHE_EXT, CET
76 is around 1.5 times faster.
77
78 If you use a cached object with a cached in memory template,
79 then CET is 50% faster.
80
81 If you use Template::Stash::XS with a cached in memory template,
82 then CET is about as fast. But if you use CGI::Ex::Template::XS,
83 the CETX is faster still (about twice as fast as CET).
84
85 It is pretty hard to beat the speed of XS stash with compiled in
86 memory templates. Many systems don't have access to those so
87 CET may make more sense. Hopefully as TT is revised, many of the CET
88 speed advantages can be incorporated so that the core TT is just as
89 fast or faster. This was last updated at version 2.10 of CET and
90 2.18 of TT.
91
92 So should you use CGI::Ex::Template ? Well, try it out. It may
93 give you no visible improvement. Or it could.
94
95
96 =head1 PUBLIC METHODS
97
98 The following section lists most of the publicly available methods. Some less
99 commonly used public methods are listed later in this document.
100
101 =over 4
102
103 =item C<new>
104
105 my $obj = CGI::Ex::Template->new({
106 INCLUDE_PATH => ['/my/path/to/content', '/my/path/to/content2'],
107 });
108
109 Arguments may be passed as a hash or as a hashref. Returns a CGI::Ex::Template object.
110
111 There are currently no errors during CGI::Ex::Template object creation.
112
113 =item C<process>
114
115 This is the main method call for starting processing. Any errors that result in the
116 template processing being stopped will be stored and available via the ->error method.
117
118 Process takes three arguments.
119
120 $t->process($in, $swap, $out)
121 || die $t->error;
122
123 The $in argument can be any one of:
124
125 String containing the filename of the template to be processed. The filename should
126 be relative to INCLUDE_PATH. (See INCLUDE_PATH, ABSOLUTE, and RELATIVE configuration items).
127 In memory caching and file side caching are available for this type.
128
129 A reference to a scalar containing the contents of the template to be processed.
130
131 A coderef that will be called to return the contents of the template.
132
133 An open filehandle that will return the contents of the template when read.
134
135 The $swap argument should be hashref containing key value pairs that will be
136 available to variables swapped into the template. Values can be hashrefs, hashrefs
137 of hashrefs and so on, arrayrefs, arrayrefs of arrayrefs and so on, coderefs, objects,
138 and simple scalar values such as numbers and strings. See the section on variables.
139
140 The $out argument can be any one of:
141
142 undef - meaning to print the completed template to STDOUT.
143
144 String containing a filename. The completed template will be placed in the file.
145
146 A reference to a string. The contents will be appended to the scalar reference.
147
148 A coderef. The coderef will be called with the contents as a single argument.
149
150 An object that can run the method "print". The contents will be passed as
151 a single argument to print.
152
153 An arrayref. The contents will be pushed onto the array.
154
155 An open filehandle. The contents will be printed to the open handle.
156
157 Additionally - the $out argument can be configured using the OUTPUT configuration
158 item.
159
160 =item C<process_simple>
161
162 Similar to the process method but with the following restrictions:
163
164 The $in parameter is limited to a filename or a reference a string containing the contents.
165
166 The $out parameter may only be a reference to a scalar string that output will be appended to.
167
168 Additionally, the following configuration variables will be ignored: VARIABLES,
169 PRE_DEFINE, BLOCKS, PRE_PROCESS, PROCESS, POST_PROCESS, AUTO_RESET, OUTPUT.
170
171 =item C<error>
172
173 Should something go wrong during a "process" command, the error that occurred can
174 be retrieved via the error method.
175
176 $obj->process('somefile.html', {a => 'b'}, \$string_ref)
177 || die $obj->error;
178
179 =item C<define_vmethod>
180
181 This method is available for defining extra Virtual methods or filters. This method is similar
182 to Template::Stash::define_vmethod.
183
184 =back
185
186 =head1 TODO
187
188 Add HTML::Template support
189
190 =head1 HOW IS CGI::Ex::Template DIFFERENT
191
192 CET uses the same base template syntax and configuration items as TT2,
193 but the internals of CET were written from scratch. Additionally much
194 of the planned TT3 syntax is supported. The following is a list of
195 some of the ways that the configuration and syntax of CET are
196 different from that of TT2. Note: items that are planned to work in
197 TT3 are marked with (TT3).
198
199 =over 4
200
201 =item Numerical hash keys work
202
203 [% a = {1 => 2} %]
204
205 =item Quoted hash key interpolation is fine
206
207 [% a = {"$foo" => 1} %]
208
209 =item Multiple ranges in same constructor
210
211 [% a = [1..10, 21..30] %]
212
213 =item Constructor types can call virtual methods. (TT3)
214
215 [% a = [1..10].reverse %]
216
217 [% "$foo".length %]
218
219 [% 123.length %] # = 3
220
221 [% 123.4.length %] # = 5
222
223 [% -123.4.length %] # = -5 ("." binds more tightly than "-")
224
225 [% (a ~ b).length %]
226
227 [% "hi".repeat(3) %] # = hihihi
228
229 [% {a => b}.size %] # = 1
230
231 =item The "${" and "}" variable interpolators can contain expressions,
232 not just variables.
233
234 [% [0..10].${ 1 + 2 } %] # = 4
235
236 [% {ab => 'AB'}.${ 'a' ~ 'b' } %] # = AB
237
238 [% color = qw/Red Blue/; FOR [1..4] ; color.${ loop.index % color.size } ; END %]
239 # = RedBlueRedBlue
240
241 =item You can use regular expression quoting.
242
243 [% "foo".match( /(F\w+)/i ).0 %] # = foo
244
245 =item Tags can be nested.
246
247 [% f = "[% (1 + 2) %]" %][% f|eval %] # = 3
248
249 =item Arrays can be accessed with non-integer numbers.
250
251 [% [0..10].${ 2.3 } %] # = 3
252
253 =item Reserved names are less reserved. (TT3)
254
255 [% GET GET %] # gets the variable named "GET"
256
257 [% GET $GET %] # gets the variable who's name is stored in "GET"
258
259 =item Filters and SCALAR_OPS are interchangeable. (TT3)
260
261 [% a | length %]
262
263 [% b . lower %]
264
265 =item Pipe "|" can be used anywhere dot "." can be and means to call
266 the virtual method. (TT3)
267
268 [% a = {size => "foo"} %][% a.size %] # = foo
269
270 [% a = {size => "foo"} %][% a|size %] # = 1 (size of hash)
271
272 =item Pipe "|" and "." can be mixed. (TT3)
273
274 [% "aa" | repeat(2) . length %] # = 4
275
276 =item Added V2PIPE configuration item
277
278 Restores the behavior of the pipe operator to be
279 compatible with TT2.
280
281 With V2PIPE = 1
282
283 [% PROCESS a | repeat(2) %] # = value of block or file a repeated twice
284
285 With V2PIPE = 0 (default)
286
287 [% PROCESS a | repeat(2) %] # = process block or file named a ~ a
288
289 =item Added Virtual Object Namespaces. (TT3)
290
291 The Text, List, and Hash types give direct access
292 to virtual methods.
293
294 [% a = "foobar" %][% Text.length(a) %] # = 6
295
296 [% a = [1 .. 10] %][% List.size(a) %] # = 10
297
298 [% a = {a=>"A", b=>"B"} ; Hash.size(a) %] = 2
299
300 [% foo = {a => 1, b => 2}
301 | Hash.keys
302 | List.join(", ") %] # = a, b
303
304 =item Added "fmt" scalar, list, and hash virtual methods.
305
306 [% list.fmt("%s", ", ") %]
307
308 [% hash.fmt("%s => %s", "\n") %]
309
310 =item Whitespace is less meaningful. (TT3)
311
312 [% 2-1 %] # = 1 (fails in TT2)
313
314 =item Added pow operator.
315
316 [% 2 ** 3 %] [% 2 pow 3 %] # = 8 8
317
318 =item Added self modifiers (+=, -=, *=, /=, %=, **=, ~=). (TT3)
319
320 [% a = 2; a *= 3 ; a %] # = 6
321 [% a = 2; (a *= 3) ; a %] # = 66
322
323 =item Added pre and post increment and decrement (++ --). (TT3)
324
325 [% ++a ; ++a %] # = 12
326 [% a-- ; a-- %] # = 0-1
327
328 =item Added qw// contructor. (TT3)
329
330 [% a = qw(a b c); a.1 %] # = b
331
332 [% qw/a b c/.2 %] # = c
333
334 =item Added regex contructor. (TT3)
335
336 [% "FOO".match(/(foo)/i).0 %] # = FOO
337
338 [% a = /(foo)/i; "FOO".match(a).0 %] # = FOO
339
340 =item Allow for scientific notation. (TT3)
341
342 [% a = 1.2e-20 %]
343
344 [% 123.fmt('%.3e') %] # = 1.230e+02
345
346 =item Allow for hexidecimal input. (TT3)
347
348 [% a = 0xff0000 %][% a %] # = 16711680
349
350 [% a = 0xff2 / 0xd; a.fmt('%x') %] # = 13a
351
352 =item FOREACH variables can be nested.
353
354 [% FOREACH f.b = [1..10] ; f.b ; END %]
355
356 Note that nested variables are subject to scoping issues.
357 f.b will not be reset to its value before the FOREACH.
358
359 =item Post operative directives can be nested. (TT3)
360
361 Andy Wardley calls this side-by-side effect notation.
362
363 [% one IF two IF three %]
364
365 same as
366
367 [% IF three %][% IF two %][% one %][% END %][% END %]
368
369
370 [% a = [[1..3], [5..7]] %][% i FOREACH i = j FOREACH j = a %] # = 123567
371
372 =item Semi-colons on directives in the same tag are optional. (TT3)
373
374 [% SET a = 1
375 GET a
376 %]
377
378 [% FOREACH i = [1 .. 10]
379 i
380 END %]
381
382 Note: a semi-colon is still required in front of any block directive
383 that can be used as a post-operative directive.
384
385 [% 1 IF 0
386 2 %] # prints 2
387
388 [% 1; IF 0
389 2
390 END %] # prints 1
391
392 =item CATCH blocks can be empty.
393
394 TT2 requires them to contain something.
395
396 =item Added a DUMP directive.
397
398 Used for Data::Dumpering the passed variable or expression.
399
400 [% DUMP a.a %]
401
402 =item Added CONFIG directive.
403
404 [% CONFIG
405 ANYCASE => 1
406 PRE_CHOMP => '-'
407 %]
408
409 =item Configuration options can use lowercase names instead
410 of the all uppercase names that TT2 uses.
411
412 my $t = CGI::Ex::Template->new({
413 anycase => 1,
414 interpolate => 1,
415 });
416
417 =item CET does not generate Perl code.
418
419 It generates an "opcode" tree. The opcode tree is an arrayref
420 of scalars and array refs nested as deeply as possible. This "simple"
421 structure could be shared TT implementations in other languages
422 via JSON or YAML.
423
424 =item CET uses storable for its compiled templates.
425
426 If EVAL_PERL is off, CET will not eval_string on ANY piece of information.
427
428 =item There is eval_filter and MACRO recursion protection
429
430 You can control the nested nature of eval_filter and MACRO
431 recursion using the MAX_EVAL_RECURSE and MAX_MACRO_RECURSE
432 configuration items.
433
434 =item There is no context.
435
436 CET provides a context object that mimics the Template::Context
437 interface for use by some TT filters, eval perl blocks, views,
438 and plugins.
439
440 =item There is no stash.
441
442 Well there is but it isn't an object.
443
444 CET only supports the variables passed in VARIABLES, PRE_DEFINE, and
445 those passed to the process method. CET provides a stash object that
446 mimics the Template::Stash interface for use by some TT filters, eval
447 perl blocks, and plugins.
448
449 =item There is no provider.
450
451 CET uses the load_parsed_tree method to get and cache templates.
452
453 =item There is no parser/grammar.
454
455 CET has its own built-in recursive regex based parser and grammar system.
456
457 CET can actually be substituted in place of the native Template::Parser and
458 Template::Grammar in TT by using the Template::Parser::CET module. This
459 module uses the output of parse_tree to generate a TT style compiled perl
460 document.
461
462 =item The DEBUG directive is more limited.
463
464 It only understands DEBUG_DIRS (8) and DEBUG_UNDEF (2).
465
466 =item CET has better line information
467
468 When debug dirs is on, directives on different lines separated
469 by colons show the line they are on rather than a general line range.
470
471 Parse errors actually know what line and character they occured at.
472
473 =back
474
475 =head1 VARIABLES
476
477 This section discusses how to use variables and expressions in the TT
478 mini-language.
479
480 A variable is the most simple construct to insert into the TT mini
481 language. A variable name will look for the matching value inside
482 CGI::Ex::Templates internal stash of variables which is essentially a
483 hash reference. This stash is initially populated by either passing a
484 hashref as the second argument to the process method, or by setting
485 the "VARIABLES" or "PRE_DEFINE" configuration variables.
486
487 ### some sample variables
488 my %vars = (
489 one => '1.0',
490 foo => 'bar',
491 vname => 'one',
492 some_code => sub { "You passed me (".join(', ', @_).")" },
493 some_data => {
494 a => 'A',
495 bar => 3234,
496 c => [3, 1, 4, 1, 5, 9],
497 vname => 'one',
498 },
499 my_list => [20 .. 50],
500 cet => CGI::Ex::Template->new,
501 );
502
503 ### pass the variables into the CET process
504 $cet->process($template_name, \%vars)
505 || die $cet->error;
506
507 ### pass the variables during object creation (will be available to every process call)
508 my $cet = CGI::Ex::Template->new(VARIABLES => \%vars);
509
510 =head2 GETTING VARIABLES
511
512 Once you have variables defined, they can be used directly in the
513 template by using their name in the stash. Or by using the GET
514 directive.
515
516 [% foo %]
517 [% one %]
518 [% GET foo %]
519
520 Would print when processed:
521
522 bar
523 1.0
524 bar
525
526 To access members of a hashref or an arrayref, you can chain together
527 the names using a ".".
528
529 [% some_data.a %]
530 [% my_list.0] [% my_list.1 %] [% my_list.-1 %]
531 [% some_data.c.2 %]
532
533 Would print:
534
535 A
536 20 21 50
537 4
538
539 If the value of a variable is a code reference, it will be called.
540 You can add a set of parenthesis and arguments to pass arguments.
541 Arguments are variables and can be as complex as necessary.
542
543 [% some_code %]
544 [% some_code() %]
545 [% some_code(foo) %]
546 [% some_code(one, 2, 3) %]
547
548 Would print:
549
550 You passed me ().
551 You passed me ().
552 You passed me (bar).
553 You passed me (1.0, 2, 3).
554
555 If the value of a variable is an object, methods can be called using
556 the "." operator.
557
558 [% cet %]
559
560 [% cet.dump_parse_expr('1 + 2').replace('\s+', ' ') %]
561
562 Would print something like:
563
564 CGI::Ex::Template=HASH(0x814dc28)
565
566 $VAR1 = [ [ undef, '+', '1', '2' ], 0 ];
567
568 Each type of data (string, array and hash) have virtual methods
569 associated with them. Virtual methods allow for access to functions
570 that are commonly used on those types of data. For the full list of
571 built in virtual methods, please see the section titled VIRTUAL
572 METHODS
573
574 [% foo.length %]
575 [% my_list.size %]
576 [% some_data.c.join(" | ") %]
577
578 Would print:
579
580 3
581 31
582 3 | 1 | 4 | 5 | 9
583
584 It is also possible to "interpolate" variable names using a "$". This
585 allows for storing the name of a variable inside another variable. If
586 a variable name is a little more complex it can be embedded inside of
587 "${" and "}".
588
589 [% $vname %]
590 [% ${vname} %]
591 [% ${some_data.vname} %]
592 [% some_data.$foo %]
593 [% some_data.${foo} %]
594
595 Would print:
596
597 1.0
598 1.0
599 1.0
600 3234
601 3234
602
603 In CET it is also possible to embed any expression (non-directive) in
604 "${" and "}" and it is possible to use non-integers for array access.
605 (This is not available in TT2)
606
607 [% ['a'..'z'].${ 2.3 } %]
608 [% {ab => 'AB'}.${ 'a' ~ 'b' } %]
609 [% color = qw/Red Blue/; FOR [1..4] ; color.${ loop.index % color.size } ; END %]
610
611 Would print:
612
613 c
614 AB
615 RedBlueRedBlue
616
617 =head2 SETTING VARIABLES.
618
619 To define variables during processing, you can use the = operator. In
620 most cases this is the same as using the SET directive.
621
622 [% a = 234 %][% a %]
623 [% SET b = "Hello" %][% b %]
624
625 Would print:
626
627 234
628 Hello
629
630 It is also possible to create arrayrefs and hashrefs.
631
632 [% a = [1, 2, 3] %]
633 [% b = {key1 => 'val1', 'key2' => 'val2'} %]
634
635 [% a.1 %]
636 [% b.key1 %] [% b.key2 %]
637
638 Would print:
639
640 2
641 val1 val2
642
643 It is possible to set multiple values in the same SET directive.
644
645 [% SET a = 'A'
646 b = 'B'
647 c = 'C' %]
648 [% a %] [% b %] [% c %]
649
650 Would print:
651
652 A B C
653
654 It is also possible to unset variables, or to set members of
655 nested data structures.
656
657 [% a = 1 %]
658 [% SET a %]
659
660 [% b.0.c = 37 %]
661
662 ([% a %])
663 [% b.0.c %]
664
665 Would print
666
667 ()
668 37
669
670 =head1 LITERALS AND CONSTRUCTORS
671
672 The following are the types of literals (numbers and strings) and
673 constructors (hash and array constructs) allowed in CET. They can be
674 used as arguments to functions, in place of variables in directives,
675 and in place of variables in expressions. In CET it is also possible
676 to call virtual methods on literal values.
677
678 =over 4
679
680 =item Integers and Numbers.
681
682 [% 23423 %] Prints an integer.
683 [% 3.14159 %] Prints a number.
684 [% pi = 3.14159 %] Sets the value of the variable.
685 [% 3.13159.length %] Prints 7 (the string length of the number)
686
687 Scientific notation is supported.
688
689 [% 314159e-5 + 0 %] Prints 3.14159.
690
691 [% .0000001.fmt('%.1e') %] Prints 1.0e-07
692
693 Hexidecimal input is also supported.
694
695 [% 0xff + 0 %] Prints 255
696
697 [% 48875.fmt('%x') %] Prints beeb
698
699 =item Single quoted strings.
700
701 Returns the string. No variable interpolation happens.
702
703 [% 'foobar' %] Prints "foobar".
704 [% '$foo\n' %] Prints "$foo\\n". # the \\n is a literal "\" and an "n"
705 [% 'That\'s nice' %] Prints "That's nice".
706 [% str = 'A string' %] Sets the value of str.
707 [% 'A string'.split %] Splits the string on ' ' and returns the list.
708
709 Note: virtual methods can only be used on literal strings in CET, not in TT.
710
711 You may also embed the current tags in strings (CET only).
712
713 [% '[% 1 + 2 %]' | eval %] Prints "3"
714
715 =item Double quoted strings.
716
717 Returns the string. Variable interpolation happens.
718
719 [% "foobar" %] Prints "foobar".
720 [% "$foo" %] Prints "bar" (assuming the value of foo is bar).
721 [% "${foo}" %] Prints "bar" (assuming the value of foo is bar).
722 [% "foobar\n" %] Prints "foobar\n". # the \n is a newline.
723 [% str = "Hello" %] Sets the value of str.
724 [% "foo".replace('foo','bar') %] Prints "bar".
725
726 Note: virtual methods can only be used on literal strings in CET, not in TT.
727
728 You may also embed the current tags in strings (CET only).
729
730 [% "[% 1 + 2 %]" | eval %] Prints "3"
731
732 =item Array Constructs.
733
734 [% [1, 2, 3] %] Prints something like ARRAY(0x8309e90).
735 [% array1 = [1 .. 3] %] Sets the value of array1.
736 [% array2 = [foo, 'a', []] %] Sets the value of array2.
737 [% [4, 5, 6].size %] Prints 3.
738 [% [7, 8, 9].reverse.0 %] Prints 9.
739
740 Note: virtual methods can only be used on array contructs in CET, not in TT.
741
742 =item Quoted Array Constructs.
743
744 [% qw/1 2 3/ %] Prints something like ARRAY(0x8309e90).
745 [% array1 = qw{Foo Bar Baz} %] Sets the value of array1.
746 [% qw[4 5 6].size %] Prints 3.
747 [% qw(Red Blue).reverse.0 %] Prints Blue.
748
749 Note: this works in CET and is planned for TT3.
750
751 =item Hash Constructs.
752
753 [% {foo => 'bar'} %] Prints something like HASH(0x8305880)
754 [% hash = {foo => 'bar', c => {}} %] Sets the value of hash.
755 [% {a => 'A', b => 'B'}.size %] Prints 2.
756 [% {'a' => 'A', 'b' => 'B'}.size %] Prints 2.
757 [% name = "Tom" %]
758 [% {Tom => 'You are Tom',
759 Kay => 'You are Kay'}.$name %] Prints You are Tom
760
761 Note: virtual methods can only be used on hash contructs in CET, not in TT.
762
763 =item Regex Constructs.
764
765 [% /foo/ %] Prints (?-xism:foo)
766 [% a = /(foo)/i %][% "FOO".match(a).0 %] Prints FOO
767
768 Note: this works in CET and is planned for TT3.
769
770 =head1 EXPRESSIONS
771
772 Expressions are one or more variables or literals joined together with
773 operators. An expression can be used anywhere a variable can be used
774 with the exception of the variable name in the SET directive, and the
775 filename of PROCESS, INCLUDE, WRAPPER, and INSERT.
776
777 The following section shows some samples of expressions. For a full
778 list of available operators, please see the section titled OPERATORS.
779
780 [% 1 + 2 %] Prints 3
781 [% 1 + 2 * 3 %] Prints 7
782 [% (1 + 2) * 3 %] Prints 9
783
784 [% x = 2 %]
785 [% y = 3 %]
786 [% z = x * (y - 1) %] Prints 4
787
788 =head1 VIRTUAL METHODS
789
790 The following is the list of builtin virtual methods and filters that
791 can be called on each type of data.
792
793 In CGI::Ex::Template, the "|" operator can be used to call virtual
794 methods just the same way that the "." operator can. The main
795 difference between the two is that on access to hashrefs or objects,
796 the "|" means to always call the virtual method or filter rather than
797 looking in the hashref for a key by that name, or trying to call that
798 method on the object. This is similar to how TT3 will function.
799
800 Virtual methods are also made available via Virtual Objects which
801 are discussed in a later section.
802
803 =head2 SCALAR VIRTUAL METHODS AND FILTERS
804
805 The following is the list of builtin virtual methods and filters that
806 can be called on scalar data types. In CET and TT3, filters and
807 virtual methods are more closely related than in TT2. In general
808 anywhere a virtual method can be used a filter can be used also - and
809 likewise all scalar virtual methods can be used as filters.
810
811 In addition to the filters listed below, CET will automatically load
812 Template::Filters and use them if Template::Toolkit is installed.
813
814 In addition to the scalar virtual methods, any scalar will be
815 automatically converted to a single item list if a list virtual method
816 is called on it.
817
818 Scalar virtual methods are also available through the "Text" virtual
819 object (except for true filters such as eval and redirect).
820
821 =over 4
822
823 =item '0'
824
825 [% item = 'foo' %][% item.0 %] Returns foo.
826
827 Allows for scalars to mask as arrays (scalars already will, but this
828 allows for more direct access).
829
830 =item chunk
831
832 [% item.chunk(60).join("\n") %] Split string up into a list of chunks of text 60 chars wide.
833
834 =item collapse
835
836 [% item.collapse %] Strip leading and trailing whitespace and collapse all other space to one space.
837
838 =item defined
839
840 [% item.defined %] Always true - because the undef sub translates all undefs to ''.
841
842 =item indent
843
844 [% item.indent(3) %] Indent that number of spaces.
845
846 [% item.indent("Foo: ") %] Add the string "Foo: " to the beginning of every line.
847
848 =item eval
849
850 [% item.eval %]
851
852 Process the string as though it was a template. This will start the parsing
853 engine and will use the same configuration as the current process. CET is several times
854 faster at doing this than TT is and is considered acceptable.
855
856 This is a filter and is not available via the Text virtual object.
857
858 =item evaltt
859
860 Same as the eval filter.
861
862 =item file
863
864 Same as the redirect filter.
865
866 =item fmt
867
868 [% item.fmt('%d') %]
869 [% item.fmt('%6s') %]
870 [% item.fmt('%*s', 6) %]
871
872 Similar to format. Returns a string formatted with the passed pattern. Default pattern is %s.
873
874 =item format
875
876 [% item.format('%d') %]
877 [% item.format('%6s') %]
878 [% item.format('%*s', 6) %]
879
880 Print the string out in the specified format. It is similar to
881 the "fmt" virtual method, except that the item is split on newline and each line is
882 processed separately.
883
884 =item hash
885
886 [% item.hash %] Returns a one item hash with a key of "value" and a value of the item.
887
888 =item html
889
890 [% item.html %] Performs a very basic html encoding (swaps out &, <, > and " for the html entities)
891
892 =item int
893
894 [% item.int %] Return the integer portion of the value (0 if none).
895
896 =item lcfirst
897
898 [% item.lcfirst %] Capitalize the leading letter.
899
900 =item length
901
902 [% item.length %] Return the length of the string.
903
904 =item list
905
906 [% item.list %] Returns a list with a single value of the item.
907
908 =item lower
909
910 [% item.lower %] Return a lower-casified string.
911
912 =item match
913
914 [% item.match("(\w+) (\w+)") %] Return a list of items matching the pattern.
915
916 [% item.match("(\w+) (\w+)", 1) %] Same as before - but match globally.
917
918 In CGI::Ex::Template and TT3 you can use regular expressions notation as well.
919
920 [% item.match( /(\w+) (\w+)/ ) %] Same as before.
921
922 [% item.match( m{(\w+) (\w+)} ) %] Same as before.
923
924 =item null
925
926 [% item.null %] Do nothing.
927
928 =item rand
929
930 [% item = 10; item.rand %] Returns a number greater or equal to 0 but less than 10.
931 [% 1.rand %]
932
933 Note: This filter is not available as of TT2.15.
934
935 =item remove
936
937 [% item.remove("\s+") %] Same as replace - but is global and replaces with nothing.
938
939 =item redirect
940
941 [% item.redirect("output_file.html") %]
942
943 Writes the contents out to the specified file. The filename
944 must be relative to the OUTPUT_PATH configuration variable and the OUTPUT_PATH variable must be set.
945
946 This is a filter and is not available via the Text virtual object.
947
948 =item repeat
949
950 [% item.repeat(3) %] Repeat the item 3 times
951
952 [% item.repeat(3, ' | ') %] Repeat the item 3 times separated with ' | '
953
954 =item replace
955
956 [% item.replace("\s+", "&nbsp;") %] Globally replace all space with &nbsp;
957
958 [% item.replace("foo", "bar", 0) %] Replace only the first instance of foo with bar.
959
960 [% item.replace("(\w+)", "($1)") %] Surround all words with parenthesis.
961
962 In CGI::Ex::Template and TT3 you may also use normal regular expression notation.
963
964 [% item.replace(/(\w+)/, "($1)") %] Same as before.
965
966 =item search
967
968 [% item.search("(\w+)") %] Tests if the given pattern is in the string.
969
970 In CGI::Ex::Template and TT3 you may also use normal regular expression notation.
971
972 [% item.search(/(\w+)/, "($1)") %] Same as before.
973
974 =item size
975
976 [% item.size %] Always returns 1.
977
978 =item split
979
980 [% item.split %] Returns an arrayref from the item split on " "
981
982 [% item.split("\s+") %] Returns an arrayref from the item split on /\s+/
983
984 [% item.split("\s+", 3) %] Returns an arrayref from the item split on /\s+/ splitting until 3 elements are found.
985
986 In CGI::Ex::Template and TT3 you may also use normal regular expression notation.
987
988 [% item.split( /\s+/, 3 ) %] Same as before.
989
990 =item stderr
991
992 [% item.stderr %] Print the item to the current STDERR handle.
993
994 =item substr
995
996 [% item.substr(i) %] Returns a substring of item starting at i and going to the end of the string.
997
998 [% item.substr(i, n) %] Returns a substring of item starting at i and going n characters.
999
1000 =item trim
1001
1002 [% item.trim %] Strips leading and trailing whitespace.
1003
1004 =item ucfirst
1005
1006 [% item.ucfirst %] Lower-case the leading letter.
1007
1008 =item upper
1009
1010 [% item.upper %] Return a upper-casified string.
1011
1012 =item uri
1013
1014 [% item.uri %] Perform a very basic URI encoding.
1015
1016 =item url
1017
1018 [% item.url %] Perform a URI encoding - but some characters such
1019 as : and / are left intact.
1020
1021 =back
1022
1023 =head2 LIST VIRTUAL METHODS
1024
1025 The following methods can be called on an arrayref type data structures (scalar
1026 types will automatically promote to a single element list and call these methods
1027 if needed):
1028
1029 Additionally, list virtual methods can be accessed via the List
1030 Virtual Object.
1031
1032 =over 4
1033
1034 =item fmt
1035
1036 [% mylist.fmt('%s', ', ') %]
1037 [% mylist.fmt('%6s', ', ') %]
1038 [% mylist.fmt('%*s', ', ', 6) %]
1039
1040 Passed a pattern and an string to join on. Returns a string of the values of the list
1041 formatted with the passed pattern and joined with the passed string.
1042 Default pattern is %s and the default join string is a space.
1043
1044 =item first
1045
1046 [% mylist.first(3) %] Returns a list of the first 3 items in the list.
1047
1048 =item grep
1049
1050 [% mylist.grep("^\w+\.\w+$") %] Returns a list of all items matching the pattern.
1051
1052 =item hash
1053
1054 [% mylist.hash %] Returns a hashref with the array indexes as keys and the values as values.
1055
1056 =item join
1057
1058 [% mylist.join %] Joins on space.
1059 [% mylist.join(", ") Joins on the passed argument.
1060
1061 =item last
1062
1063 [% mylist.last(3) %] Returns a list of the last 3 items in the list.
1064
1065 =item list
1066
1067 [% mylist.list %] Returns a reference to the list.
1068
1069 =item max
1070
1071 [% mylist.max %] Returns the last item in the array.
1072
1073 =item merge
1074
1075 [% mylist.merge(list2) %] Returns a new list with all defined items from list2 added.
1076
1077 =item nsort
1078
1079 [% mylist.nsort %] Returns the numerically sorted items of the list. If the items are
1080 hashrefs, a key containing the field to sort on can be passed.
1081
1082 =item pop
1083
1084 [% mylist.pop %] Removes and returns the last element from the arrayref (the stash is modified).
1085
1086 =item push
1087
1088 [% mylist.push(23) %] Adds an element to the end of the arrayref (the stash is modified).
1089
1090 =item pick
1091
1092 [% mylist.pick %] Returns a random item from the list.
1093 [% ['a' .. 'z'].pick %]
1094
1095 An additional numeric argument is how many items to return.
1096
1097 [% ['a' .. 'z'].pick(8).join('') %]
1098
1099 Note: This filter is not available as of TT2.15.
1100
1101 =item reverse
1102
1103 [% mylist.reverse %] Returns the list in reverse order.
1104
1105 =item shift
1106
1107 [% mylist.shift %] Removes and returns the first element of the arrayref (the stash is modified).
1108
1109 =item size
1110
1111 [% mylist.size %] Returns the number of elements in the array.
1112
1113 =item slice
1114
1115 [% mylist.slice(i, n) %] Returns a list from the arrayref beginning at index i and continuing for n items.
1116
1117 =item sort
1118
1119 [% mylist.sort %] Returns the alphabetically sorted items of the list. If the items are
1120 hashrefs, a key containing the field to sort on can be passed.
1121
1122 =item splice
1123
1124 [% mylist.splice(i, n) %] Removes items from array beginning at i and continuing for n items.
1125
1126 [% mylist.splice(i, n, list2) %] Same as before, but replaces removed items with the items
1127 from list2.
1128
1129 =item unique
1130
1131 [% mylist.unique %] Return a list of the unique items in the array.
1132
1133 =item unshift
1134
1135 [% mylist.unshift(23) %] Adds an item to the beginning of the arrayref.
1136
1137 =back 4
1138
1139 =head2 HASH VIRTUAL METHODS
1140
1141 The following methods can be called on hash type data structures:
1142
1143 Additionally, list virtual methods can be accessed via the Hash
1144 Virtual Object.
1145
1146 =over 4
1147
1148 =item fmt
1149
1150 [% myhash.fmt('%s => %s', "\n") %]
1151 [% myhash.fmt('%4s => %5s', "\n") %]
1152 [% myhash.fmt('%*s => %*s', "\n", 4, 5) %]
1153
1154 Passed a pattern and an string to join on. Returns a string of the key/value pairs
1155 of the hash formatted with the passed pattern and joined with the passed string.
1156 Default pattern is "%s\t%s" and the default join string is a newline.
1157
1158 =item defined
1159
1160 [% myhash.defined('a') %] Checks if a is defined in the hash.
1161
1162 =item delete
1163
1164 [% myhash.delete('a') %] Deletes the item from the hash.
1165
1166 Unlink Perl the value is not returned. Multiple values may be passed
1167 and represent the keys to be deleted.
1168
1169 =item each
1170
1171 [% myhash.each.join(", ") %] Turns the contents of the hash into a list - subject
1172 to change as TT is changing the operations of each and list.
1173
1174 =item exists
1175
1176 [% myhash.exists('a') %] Checks if a is in the hash.
1177
1178 =item hash
1179
1180 [% myhash.hash %] Returns a reference to the hash.
1181
1182 =item import
1183
1184 [% myhash.import(hash2) %] Overlays the keys of hash2 over the keys of myhash.
1185
1186 =item item
1187
1188 [% myhash.item(key) %] Returns the hashes value for that key.
1189
1190 =item items
1191
1192 [% myhash.items %] Returns a list of the key and values (flattened hash)
1193
1194 =item keys
1195
1196 [% myhash.keys.join(', ') %] Returns an arrayref of the keys of the hash.
1197
1198 =item list
1199
1200 [% myhash.list %] Returns an arrayref with the hash as a single value (subject to change).
1201
1202 =item pairs
1203
1204 [% myhash.pairs %] Returns an arrayref of hashrefs where each hash contains {key => $key, value => $value}
1205 for each value of the hash.
1206
1207 =item nsort
1208
1209 [% myhash.nsort.join(", ") %] Returns a numerically sorted list of the keys.
1210
1211 =item size
1212
1213 [% myhash.size %] Returns the number of key/value pairs in the hash.
1214
1215 =item sort
1216
1217 [% myhash.sort.join(", ") Returns an alphabetically sorted list.
1218
1219 =item values
1220
1221 [% myhash.values.join(', ') %] Returns an arrayref of the values of the hash.
1222
1223 =back
1224
1225 =head1 VIRTUAL OBJECTS
1226
1227 TT3 has a concept of Text, List, and Hash virtual objects which provide
1228 direct access to the scalar, list, and hash virtual methods. In the TT3
1229 engine this will allow for more concise generated code. Because CET does
1230 not generated perl code to be executed later, CET provides for these virtual
1231 objects but does so as more of a namespace (using the methods does not
1232 provide a speed optimization in your template - just may help clarify things).
1233
1234 [% a = "foo"; a.length %] => 3
1235
1236 [% a = "foo"; Text.length(a) %] => 3
1237
1238 [% a = Text.new("foo"); a.length %] => 3
1239
1240
1241 [% a = [1 .. 30]; a.size %] => 30
1242
1243 [% a = [1 .. 30]; List.size(a) %] => 30
1244
1245 [% a = List.new(1 .. 30); a.size %] => 30
1246
1247
1248 [% a = {a => 1, b => 2}; a.size %] => 2
1249
1250 [% a = {a => 1, b => 2}; Hash.size(a) %] => 2
1251
1252 [% a = Hash.new({a => 1, b => 2}); a.size %] => 2
1253
1254 [% a = Hash.new(a => 1, b => 2); a.size %] => 2
1255
1256 [% a = Hash.new(a = 1, b = 2); a.size %] => 2
1257
1258 [% a = Hash.new('a', 1, 'b', 2); a.size %] => 2
1259
1260 One limitation is that if you pass a key named "Text",
1261 "List", or "Hash" in your variable stash - the corresponding
1262 virtual object will be hidden.
1263
1264 Additionally, you can use all of the Virtual object methods with
1265 the pipe operator.
1266
1267 [% {a => 1, b => 2}
1268 | Hash.keys
1269 | List.join(", ") %] => a, b
1270
1271 Again, there aren't any speed optimizations to using the virtual
1272 objects in CET, but it can help clarify the intent in some cases.
1273
1274 Note: these aren't really objects. All of the "virtual objects" are
1275 references to the $SCALAR_OPS, $LIST_OPS, and $HASH_OPS hashes
1276 found in the $VOBJS hash of CGI::Ex::Template.
1277
1278 =head1 DIRECTIVES
1279
1280 This section contains the alphabetical list of DIRECTIVES available in
1281 the TT language. DIRECTIVES are the "functions" and control
1282 structures of the Template Toolkit mini-language. For further
1283 discussion and examples beyond what is listed below, please refer to
1284 the TT directives documentation.
1285
1286 [% IF 1 %]One[% END %]
1287 [% FOREACH a = [1 .. 3] %]
1288 a = [% a %]
1289 [% END %]
1290
1291 [% SET a = 1 %][% SET a = 2 %][% GET a %]
1292
1293 Multiple directives can be inside the same set of '[%' and '%]' tags
1294 as long as they are separated by space or semi-colons (;). Any block
1295 directive that can also be used as a post-operative directive (such as
1296 IF, WHILE, FOREACH, UNLESS, FILTER, and WRAPPER) must be separated
1297 from preceding directives with a semi-colon if it is being used as a
1298 block directive. It is more safe to always use a semi-colon. Note:
1299 separating by space is only available in CET but is a planned TT3
1300 feature.
1301
1302 [% SET a = 1 ; SET a = 2 ; GET a %]
1303 [% SET a = 1
1304 SET a = 2
1305 GET a
1306 %]
1307
1308 [% GET 1
1309 IF 0 # is a post-operative
1310 GET 2 %] # prints 2
1311
1312 [% GET 1;
1313 IF 0 # it is block based
1314 GET 2
1315 END
1316 %] # prints 1
1317
1318 The following is the list of directives.
1319
1320 =over 4
1321
1322 =item C<BLOCK>
1323
1324 Saves a block of text under a name for later use in PROCESS, INCLUDE,
1325 and WRAPPER directives. Blocks may be placed anywhere within the
1326 template being processed including after where they are used.
1327
1328 [% BLOCK foo %]Some text[% END %]
1329 [% PROCESS foo %]
1330
1331 Would print
1332
1333 Some text
1334
1335 [% INCLUDE foo %]
1336 [% BLOCK foo %]Some text[% END %]
1337
1338 Would print
1339
1340 Some text
1341
1342 Anonymous BLOCKS can be used for capturing.
1343
1344 [% a = BLOCK %]Some text[% END %][% a %]
1345
1346 Would print
1347
1348 Some text
1349
1350 Anonymous BLOCKS can be used with macros.
1351
1352
1353 =item C<BREAK>
1354
1355 Alias for LAST. Used for exiting FOREACH and WHILE loops.
1356
1357 =item C<CALL>
1358
1359 Calls the variable (and any underlying coderefs) as in the GET method, but
1360 always returns an empty string.
1361
1362 =item C<CASE>
1363
1364 Used with the SWITCH directive. See the L</"SWITCH"> directive.
1365
1366 =item C<CATCH>
1367
1368 Used with the TRY directive. See the L</"TRY"> directive.
1369
1370 =item C<CLEAR>
1371
1372 Clears any of the content currently generated in the innermost block
1373 or template. This can be useful when used in conjunction with the TRY
1374 statement to clear generated content if an error occurs later.
1375
1376 =item C<CONFIG>
1377
1378 Allow for changing the value of some compile time and runtime configuration
1379 options.
1380
1381 [% CONFIG
1382 ANYCASE => 1
1383 PRE_CHOMP => '-'
1384 %]
1385
1386 The following compile time configuration options may be set:
1387
1388 ANYCASE
1389 INTERPOLATE
1390 PRE_CHOMP
1391 POST_CHOMP
1392 V1DOLLAR
1393 V2PIPE
1394
1395 The following runtime configuration options may be set:
1396
1397 DUMP
1398
1399 If non-named parameters as passed, they will show the current configuration:
1400
1401 [% CONFIG ANYCASE, PRE_CHOMP %]
1402
1403 CONFIG ANYCASE = undef
1404 CONFIG PRE_CHOMP = undef
1405
1406 =item C<DEBUG>
1407
1408 Used to reset the DEBUG_FORMAT configuration variable, or to turn
1409 DEBUG statements on or off. This only has effect if the DEBUG_DIRS or
1410 DEBUG_ALL flags were passed to the DEBUG configuration variable.
1411
1412 [% DEBUG format '($file) (line $line) ($text)' %]
1413 [% DEBUG on %]
1414 [% DEBUG off %]
1415
1416 =item C<DEFAULT>
1417
1418 Similar to SET, but only sets the value if a previous value was not
1419 defined or was zero length.
1420
1421 [% DEFAULT foo = 'bar' %][% foo %] => 'bar'
1422
1423 [% foo = 'baz' %][% DEFAULT foo = 'bar' %][% foo %] => 'baz'
1424
1425 =item C<DUMP>
1426
1427 DUMP inserts a Data::Dumper printout of the variable or expression.
1428 If no argument is passed it will dump the entire contents of the
1429 current variable stash (with private keys removed).
1430
1431 The output also includes the current file and line number that the
1432 DUMP directive was called from.
1433
1434 See the DUMP configuration item for ways to customize and control
1435 the output available to the DUMP directive.
1436
1437 [% DUMP %] # dumps everything
1438
1439 [% DUMP 1 + 2 %]
1440
1441 =item C<ELSE>
1442
1443 Used with the IF directive. See the L</"IF"> directive.
1444
1445 =item C<ELSIF>
1446
1447 Used with the IF directive. See the L</"IF"> directive.
1448
1449 =item C<END>
1450
1451 Used to end a block directive.
1452
1453 =item C<FILTER>
1454
1455 Used to apply different treatments to blocks of text. It may operate as a BLOCK
1456 directive or as a post operative directive. CET supports all of the filters in
1457 Template::Filters. The lines between scalar virtual methods and filters is blurred (or
1458 non-existent) in CET. Anything that is a scalar virtual method may be used as a FILTER.
1459
1460 TODO - enumerate the at least 7 ways to pass and use filters.
1461
1462 =item C<'|'>
1463
1464 Alias for the FILTER directive. Note that | is similar to the
1465 '.' in CGI::Ex::Template. Therefore a pipe cannot be used directly after a
1466 variable name in some situations (the pipe will act only on that variable).
1467 This is the behavior employed by TT3. To get the TT2 behavior for a PIPE, use
1468 the V2PIPE configuration item.
1469
1470 =item C<FINAL>
1471
1472 Used with the TRY directive. See the L</"TRY"> directive.
1473
1474 =item C<FOR>
1475
1476 Alias for FOREACH
1477
1478 =item C<FOREACH>
1479
1480 Allows for iterating over the contents of any arrayref. If the variable is not an
1481 arrayref, it is automatically promoted to one.
1482
1483 [% FOREACH i IN [1 .. 3] %]
1484 The variable i = [% i %]
1485 [%~ END %]
1486
1487 [% a = [1 .. 3] %]
1488 [% FOREACH j IN a %]
1489 The variable j = [% j %]
1490 [%~ END %]
1491
1492 Would print:
1493
1494 The variable i = 1
1495 The variable i = 2
1496 The variable i = 3
1497
1498 The variable j = 1
1499 The variable j = 2
1500 The variable j = 3
1501
1502 You can also use the "=" instead of "IN" or "in".
1503
1504 [% FOREACH i = [1 .. 3] %]
1505 The variable i = [% i %]
1506 [%~ END %]
1507
1508 Same as before.
1509
1510 Setting into a variable is optional.
1511
1512 [% a = [1 .. 3] %]
1513 [% FOREACH a %] Hi [% END %]
1514
1515 Would print:
1516
1517 hi hi hi
1518
1519 If the item being iterated is a hashref and the FOREACH does not
1520 set into a variable, then values of the hashref are copied into
1521 the variable stash.
1522
1523 [% FOREACH [{a => 1}, {a => 2}] %]
1524 Key a = [% a %]
1525 [%~ END %]
1526
1527 Would print:
1528
1529 Key a = 1
1530 Key a = 2
1531
1532 The FOREACH process uses the CGI::Ex::Template::Iterator class to handle
1533 iterations (It is compatible with Template::Iterator). During the FOREACH
1534 loop an object blessed into the iterator class is stored in the variable "loop".
1535
1536 The loop variable provides the following information during a FOREACH:
1537
1538 index - the current index
1539 max - the max index of the list
1540 size - the number of items in the list
1541 count - index + 1
1542 number - index + 1
1543 first - true if on the first item
1544 last - true if on the last item
1545 next - return the next item in the list
1546 prev - return the previous item in the list
1547
1548 The following:
1549
1550 [% FOREACH [1 .. 3] %] [% loop.count %]/[% loop.size %] [% END %]
1551
1552 Would print:
1553
1554 1/3 2/3 3/3
1555
1556 The iterator is also available using a plugin. This allows for access
1557 to multiple "loop" variables in a nested FOREACH directive.
1558
1559 [%~ USE outer_loop = Iterator(["a", "b"]) %]
1560 [%~ FOREACH i = outer_loop %]
1561 [%~ FOREACH j = ["X", "Y"] %]
1562 [% outer_loop.count %]-[% loop.count %] = ([% i %] and [% j %])
1563 [%~ END %]
1564 [%~ END %]
1565
1566 Would print:
1567
1568 1-1 = (a and X)
1569 1-2 = (a and Y)
1570 2-1 = (b and X)
1571 2-2 = (b and Y)
1572
1573 FOREACH may also be used as a post operative directive.
1574
1575 [% "$i" FOREACH i = [1 .. 5] %] => 12345
1576
1577 =item C<GET>
1578
1579 Return the value of a variable or expression.
1580
1581 [% GET a %]
1582
1583 The GET keyword may be omitted.
1584
1585 [% a %]
1586
1587 [% 7 + 2 - 3 %] => 6
1588
1589 See the section on VARIABLES.
1590
1591 =item C<IF (IF / ELSIF / ELSE)>
1592
1593 Allows for conditional testing. Expects an expression as its only
1594 argument. If the expression is true, the contents of its block are
1595 processed. If false, the processor looks for an ELSIF block. If an
1596 ELSIF's expression is true then it is processed. Finally it looks for
1597 an ELSE block which is processed if none of the IF or ELSIF's
1598 expressions were true.
1599
1600 [% IF a == b %]A equaled B[% END %]
1601
1602 [% IF a == b -%]
1603 A equaled B
1604 [%- ELSIF a == c -%]
1605 A equaled C
1606 [%- ELSE -%]
1607 Couldn't determine that A equaled anything.
1608 [%- END %]
1609
1610 IF may also be used as a post operative directive.
1611
1612 [% 'A equaled B' IF a == b %]
1613
1614 =item C<INCLUDE>
1615
1616 Parse the contents of a file or block and insert them. Variables defined
1617 or modifications made to existing variables are discarded after
1618 a template is included.
1619
1620 [% INCLUDE path/to/template.html %]
1621
1622 [% INCLUDE "path/to/template.html" %]
1623
1624 [% file = "path/to/template.html" %]
1625 [% INCLUDE $file %]
1626
1627 [% BLOCK foo %]This is foo[% END %]
1628 [% INCLUDE foo %]
1629
1630 Arguments may also be passed to the template:
1631
1632 [% INCLUDE "path/to/template.html" a = "An arg" b = "Another arg" %]
1633
1634 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1635 or RELATIVE configuration items are set.
1636
1637 Multiple filenames can be passed by separating them with a plus, a space,
1638 or commas (TT2 doesn't support the comma). Any supplied arguments will
1639 be used on all templates.
1640
1641 [% INCLUDE "path/to/template.html",
1642 "path/to/template2.html" a = "An arg" b = "Another arg" %]
1643
1644 =item C<INSERT>
1645
1646 Insert the contents of a file without template parsing.
1647
1648 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1649 or RELATIVE configuration items are set.
1650
1651 Multiple filenames can be passed by separating them with a plus, a space,
1652 or commas (TT2 doesn't support the comma).
1653
1654 [% INSERT "path/to/template.html",
1655 "path/to/template2.html" %]
1656
1657 =item C<LAST>
1658
1659 Used to exit out of a WHILE or FOREACH loop.
1660
1661 =item C<MACRO>
1662
1663 Takes a directive and turns it into a variable that can take arguments.
1664
1665 [% MACRO foo(i, j) BLOCK %]You passed me [% i %] and [% j %].[% END %]
1666
1667 [%~ foo("a", "b") %]
1668 [% foo(1, 2) %]
1669
1670 Would print:
1671
1672 You passed me a and b.
1673 You passed me 1 and 2.
1674
1675 Another example:
1676
1677 [% MACRO bar(max) FOREACH i = [1 .. max] %]([% i %])[% END %]
1678
1679 [%~ bar(4) %]
1680
1681 Would print:
1682
1683 (1)(2)(3)(4)
1684
1685 =item C<META>
1686
1687 Used to define variables that will be available via either the
1688 template or component namespace.
1689
1690 Once defined, they cannot be overwritten.
1691
1692 [% template.foobar %]
1693 [%~ META foobar = 'baz' %]
1694 [%~ META foobar = 'bing' %]
1695
1696 Would print:
1697
1698 baz
1699
1700 =item C<NEXT>
1701
1702 Used to go to the next iteration of a WHILE or FOREACH loop.
1703
1704 =item C<PERL>
1705
1706 Only available if the EVAL_PERL configuration item is true (default is false).
1707
1708 Allow eval'ing the block of text as perl. The block will be parsed and then eval'ed.
1709
1710 [% a = "BimBam" %]
1711 [%~ PERL %]
1712 my $a = "[% a %]";
1713 print "The variable \$a was \"$a\"";
1714 $stash->set('b', "FooBar");
1715 [% END %]
1716 [% b %]
1717
1718 Would print:
1719
1720 The variable $a was "BimBam"
1721 FooBar
1722
1723 During execution, anything printed to STDOUT will be inserted into the template. Also,
1724 the $stash and $context variables are set and are references to objects that mimic the
1725 interface provided by Template::Context and Template::Stash. These are provided for
1726 compatibility only. $self contains the current CGI::Ex::Template object.
1727
1728 =item C<PROCESS>
1729
1730 Parse the contents of a file or block and insert them. Unlike INCLUDE,
1731 no variable localization happens so variables defined or modifications made
1732 to existing variables remain after the template is processed.
1733
1734 [% PROCESS path/to/template.html %]
1735
1736 [% PROCESS "path/to/template.html" %]
1737
1738 [% file = "path/to/template.html" %]
1739 [% PROCESS $file %]
1740
1741 [% BLOCK foo %]This is foo[% END %]
1742 [% PROCESS foo %]
1743
1744 Arguments may also be passed to the template:
1745
1746 [% PROCESS "path/to/template.html" a = "An arg" b = "Another arg" %]
1747
1748 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1749 or RELATIVE configuration items are set.
1750
1751 Multiple filenames can be passed by separating them with a plus, a space,
1752 or commas (TT2 doesn't support the comma). Any supplied arguments will
1753 be used on all templates.
1754
1755 [% PROCESS "path/to/template.html",
1756 "path/to/template2.html" a = "An arg" b = "Another arg" %]
1757
1758 =item C<RAWPERL>
1759
1760 Only available if the EVAL_PERL configuration item is true (default is false).
1761 Similar to the PERL directive, but you will need to append
1762 to the $output variable rather than just calling PRINT.
1763
1764 =item C<RETURN>
1765
1766 Used to exit the innermost block or template and continue processing
1767 in the surrounding block or template.
1768
1769 =item C<SET>
1770
1771 Used to set variables.
1772
1773 [% SET a = 1 %][% a %] => "1"
1774 [% a = 1 %][% a %] => "1"
1775 [% b = 1 %][% SET a = b %][% a %] => "1"
1776 [% a = 1 %][% SET a %][% a %] => ""
1777 [% SET a = [1, 2, 3] %][% a.1 %] => "2"
1778 [% SET a = {b => 'c'} %][% a.b %] => "c"
1779
1780 =item C<STOP>
1781
1782 Used to exit the entire process method (out of all blocks and templates).
1783 No content will be processed beyond this point.
1784
1785 =item C<SWITCH>
1786
1787 Allow for SWITCH and CASE functionality.
1788
1789 [% a = "hi" %]
1790 [% b = "bar" %]
1791 [% SWITCH a %]
1792 [% CASE "foo" %]a was foo
1793 [% CASE b %]a was bar
1794 [% CASE ["hi", "hello"] %]You said hi or hello
1795 [% CASE DEFAULT %]I don't know what you said
1796 [% END %]
1797
1798 Would print:
1799
1800 You said hi or hello
1801
1802 =item C<TAGS>
1803
1804 Change the type of enclosing braces used to delineate template tags. This
1805 remains in effect until the end of the enclosing block or template or until
1806 the next TAGS directive. Either a named set of tags must be supplied, or
1807 two tags themselves must be supplied.
1808
1809 [% TAGS html %]
1810
1811 [% TAGS <!-- --> %]
1812
1813 The named tags are (duplicated from TT):
1814
1815 asp => ['<%', '%>' ], # ASP
1816 default => ['\[%', '%\]' ], # default
1817 html => ['<!--', '-->' ], # HTML comments
1818 mason => ['<%', '>' ], # HTML::Mason
1819 metatext => ['%%', '%%' ], # Text::MetaText
1820 php => ['<\?', '\?>' ], # PHP
1821 star => ['\[\*', '\*\]' ], # TT alternate
1822 template => ['\[%', '%\]' ], # Normal Template Toolkit
1823 template1 => ['[\[%]%', '%[%\]]'], # allow TT1 style
1824 tt2 => ['\[%', '%\]' ], # TT2
1825
1826 If custom tags are supplied, by default they are escaped using
1827 quotemeta. You may also pass explicitly quoted strings,
1828 or regular expressions as arguments as well (if your
1829 regex begins with a ', ", or / you must quote it.
1830
1831 [% TAGS [<] [>] %] matches "[<] tag [>]"
1832
1833 [% TAGS '[<]' '[>]' %] matches "[<] tag [>]"
1834
1835 [% TAGS "[<]" "[>]" %] matches "[<] tag [>]"
1836
1837 [% TAGS /[<]/ /[>]/ %] matches "< tag >"
1838
1839 [% TAGS ** ** %] matches "** tag **"
1840
1841 [% TAGS /**/ /**/ %] Throws an exception.
1842
1843 =item C<THROW>
1844
1845 Allows for throwing an exception. If the exception is not caught
1846 via the TRY DIRECTIVE, the template will abort processing of the directive.
1847
1848 [% THROW mytypes.sometime 'Something happened' arg1 => val1 %]
1849
1850 See the TRY directive for examples of usage.
1851
1852 =item C<TRY>
1853
1854 The TRY block directive will catch exceptions that are thrown
1855 while processing its block (It cannot catch parse errors unless
1856 they are in included files or evaltt'ed strings. The TRY block
1857 will then look for a CATCH block that will be processed. While
1858 it is being processed, the "error" variable will be set with the thrown
1859 exception as the value. After the TRY block - the FINAL
1860 block will be ran whether or not an error was thrown (unless a CATCH
1861 block throws an error).
1862
1863 Note: Parse errors cannot be caught unless they are in an eval FILTER, or are
1864 in a separate template being INCLUDEd or PROCESSed.
1865
1866 [% TRY %]
1867 Nothing bad happened.
1868 [% CATCH %]
1869 Caught the error.
1870 [% FINAL %]
1871 This section runs no matter what happens.
1872 [% END %]
1873
1874 Would print:
1875
1876 Nothing bad happened.
1877 This section runs no matter what happens.
1878
1879 Another example:
1880
1881 [% TRY %]
1882 [% THROW "Something happened" %]
1883 [% CATCH %]
1884 Error: [% error %]
1885 Error.type: [% error.type %]
1886 Error.info: [% error.info %]
1887 [% FINAL %]
1888 This section runs no matter what happens.
1889 [% END %]
1890
1891 Would print:
1892
1893 Error: undef error - Something happened
1894 Error.type: undef
1895 Error.info: Something happened
1896 This section runs no matter what happens.
1897
1898 You can give the error a type and more information including named arguments.
1899 This information replaces the "info" property of the exception.
1900
1901 [% TRY %]
1902 [% THROW foo.bar "Something happened" "grrrr" foo => 'bar' %]
1903 [% CATCH %]
1904 Error: [% error %]
1905 Error.type: [% error.type %]
1906 Error.info: [% error.info %]
1907 Error.info.0: [% error.info.0 %]
1908 Error.info.1: [% error.info.1 %]
1909 Error.info.args.0: [% error.info.args.0 %]
1910 Error.info.foo: [% error.info.foo %]
1911 [% END %]
1912
1913 Would print something like:
1914
1915 Error: foo.bar error - HASH(0x82a395c)
1916 Error.type: foo.bar
1917 Error.info: HASH(0x82a395c)
1918 Error.info.0: Something happened
1919 Error.info.1: grrrr
1920 Error.info.args.0: Something happened
1921 Error.info.foo: bar
1922
1923 You can also give the CATCH block a type to catch. And you
1924 can nest TRY blocks. If types are specified, CET will try and
1925 find the closest matching type. Also, an error object can
1926 be re-thrown using $error as the argument to THROW.
1927
1928 [% TRY %]
1929 [% TRY %]
1930 [% THROW foo.bar "Something happened" %]
1931 [% CATCH bar %]
1932 Caught bar.
1933 [% CATCH DEFAULT %]
1934 Caught default - but rethrew.
1935 [% THROW $error %]
1936 [% END %]
1937 [% CATCH foo %]
1938 Caught foo.
1939 [% CATCH foo.bar %]
1940 Caught foo.bar.
1941 [% CATCH %]
1942 Caught anything else.
1943 [% END %]
1944
1945 Would print:
1946
1947 Caught default - but rethrew.
1948
1949 Caught foo.bar.
1950
1951 =item C<UNLESS>
1952
1953 Same as IF but condition is negated.
1954
1955 [% UNLESS 0 %]hi[% END %] => hi
1956
1957 Can also be a post operative directive.
1958
1959 =item C<USE>
1960
1961 Allows for loading a Template::Toolkit style plugin.
1962
1963 [% USE iter = Iterator(['foo', 'bar']) %]
1964 [%~ iter.get_first %]
1965 [% iter.size %]
1966
1967 Would print:
1968
1969 foo
1970 2
1971
1972 Note that it is possible to send arguments to the new object
1973 constructor. It is also possible to omit the variable name being
1974 assigned. In that case the name of the plugin becomes the variable.
1975
1976 [% USE Iterator(['foo', 'bar', 'baz']) %]
1977 [%~ Iterator.get_first %]
1978 [% Iterator.size %]
1979
1980 Would print:
1981
1982 foo
1983 3
1984
1985 Plugins that are loaded are looked up for in the namespace listed in
1986 the PLUGIN_BASE directive which defaults to Template::Plugin. So in
1987 the previous example, if Template::Toolkit was installed, the iter
1988 object would loaded by the class Template::Plugin::Iterator. In CET,
1989 an effective way to disable plugins is to set the PLUGIN_BASE to a
1990 non-existent base such as "_" (In TT it will still fall back to look
1991 in Template::Plugin).
1992
1993 Note: The iterator plugin will fall back and use
1994 CGI::Ex::Template::Iterator if Template::Toolkit is not installed. No
1995 other plugins come installed with CGI::Ex::Template.
1996
1997 The names of the Plugin being loaded from PLUGIN_BASE are case
1998 insensitive. However, using case insensitive names is bad as it
1999 requires scanning the @INC directories for any module matching the
2000 PLUGIN_BASE and caching the result (OK - not that bad).
2001
2002 If the plugin is not found and the LOAD_PERL directive is set, then
2003 CET will try and load a module by that name (note: this type of lookup
2004 is case sensitive and will not scan the @INC dirs for a matching
2005 file).
2006
2007 # The LOAD_PERL directive should be set to 1
2008 [% USE cet = CGI::Ex::Template %]
2009 [%~ cet.dump_parse_expr('2 * 3').replace('\s+', ' ') %]
2010
2011 Would print:
2012
2013 $VAR1 = [ [ undef, '*', '2', '3' ], 0 ];
2014
2015 See the PLUGIN_BASE, and PLUGINS configuration items.
2016
2017 See the documentation for Template::Manual::Plugins.
2018
2019 =item C<VIEW>
2020
2021 Implement a TT style view. For more information, please
2022 see the Template::View documentation. This DIRECTIVE
2023 will correctly parse the arguments and then pass them
2024 along to a newly created Template::View object. It
2025 will fail if Template::View can not be found.
2026
2027 =item C<WHILE>
2028
2029 Will process a block of code while a condition is true.
2030
2031 [% WHILE i < 3 %]
2032 [%~ i = i + 1 %]
2033 i = [% i %]
2034 [%~ END %]
2035
2036 Would print:
2037
2038 i = 1
2039 i = 2
2040 i = 3
2041
2042 You could also do:
2043
2044 [% i = 4 %]
2045 [% WHILE (i = i - 1) %]
2046 i = [% i %]
2047 [%~ END %]
2048
2049 Would print:
2050
2051 i = 3
2052 i = 2
2053 i = 1
2054
2055 Note that (f = f - 1) is a valid expression that returns the value
2056 of the assignment. The parenthesis are not optional.
2057
2058 WHILE has a built in limit of 1000 iterations. This is controlled by the
2059 global variable $WHILE_MAX in CGI::Ex::Template.
2060
2061 WHILE may also be used as a post operative directive.
2062
2063 [% "$i" WHILE (i = i + 1) < 7 %] => 123456
2064
2065 =item C<WRAPPER>
2066
2067 Block directive. Processes contents of its block and then passes them
2068 in the [% content %] variable to the block or filename listed in the
2069 WRAPPER tag.
2070
2071 [% WRAPPER foo b = 23 %]
2072 My content to be processed ([% b %]).[% a = 2 %]
2073 [% END %]
2074
2075 [% BLOCK foo %]
2076 A header ([% a %]).
2077 [% content %]
2078 A footer ([% a %]).
2079 [% END %]
2080
2081 This would print.
2082
2083 A header (2).
2084 My content to be processed (23).
2085 A footer (2).
2086
2087 The WRAPPER directive may also be used as a post operative directive.
2088
2089 [% BLOCK baz %]([% content %])[% END -%]
2090 [% "foobar" WRAPPER baz %]
2091
2092 Would print
2093
2094 (foobar)');
2095
2096 Multiple filenames can be passed by separating them with a plus, a space,
2097 or commas (TT2 doesn't support the comma). Any supplied arguments will
2098 be used on all templates. Wrappers are processed in reverse order, so
2099 that the first wrapper listed will surround each subsequent wrapper listed.
2100 Variables from inner wrappers are available to the next wrapper that
2101 surrounds it.
2102
2103 [% WRAPPER "path/to/outer.html",
2104 "path/to/inner.html" a = "An arg" b = "Another arg" %]
2105
2106
2107 =back
2108
2109
2110
2111 =head1 OPERATORS
2112
2113 The following operators are available in CGI::Ex::Template. Except
2114 where noted these are the same operators available in TT. They are
2115 listed in the order of their precedence (the higher the precedence the
2116 tighter it binds).
2117
2118 =over 4
2119
2120 =item C<.>
2121
2122 The dot operator. Allows for accessing sub-members, methods, or
2123 virtual methods of nested data structures.
2124
2125 my $obj->process(\$content, {a => {b => [0, {c => [34, 57]}]}}, \$output);
2126
2127 [% a.b.1.c.0 %] => 34
2128
2129 Note: on access to hashrefs, any hash keys that match the sub key name
2130 will be used before a virtual method of the same name. For example if
2131 a passed hash contained pair with a keyname "defined" and a value of
2132 "2", then any calls to hash.defined(another_keyname) would always
2133 return 2 rather than using the vmethod named "defined." To get around
2134 this limitation use the "|" operator (listed next). Also - on objects
2135 the "." will always try and call the method by that name. To always
2136 call the vmethod - use "|".
2137
2138 =item C<|>
2139
2140 The pipe operator. Similar to the dot operator. Allows for
2141 explicit calling of virtual methods and filters (filters are "merged"
2142 with virtual methods in CGI::Ex::Template and TT3) when accessing
2143 hashrefs and objects. See the note for the "." operator.
2144
2145 The pipe character is similar to TT2 in that it can be used in place
2146 of a directive as an alias for FILTER. It similar to TT3 in that it
2147 can be used for virtual method access. This duality is one source of
2148 difference between CGI::Ex::Template and TT2 compatibility. Templates
2149 that have directives that end with a variable name that then use the
2150 "|" directive to apply a filter will be broken as the "|" will be
2151 applied to the variable name.
2152
2153 The following two cases will do the same thing.
2154
2155 [% foo | html %]
2156
2157 [% foo FILTER html %]
2158
2159 Though they do the same thing, internally, foo|html is stored as a
2160 single variable while "foo FILTER html" is stored as the variable foo
2161 which is then passed to the FILTER html.
2162
2163 A TT2 sample that would break in CGI::Ex::Template or TT3 is:
2164
2165 [% PROCESS foo a = b | html %]
2166
2167 Under TT2 the content returned by "PROCESS foo a = b" would all be
2168 passed to the html filter. Under CGI::Ex::Template and TT3, b would
2169 be passed to the html filter before assigning it to the variable "a"
2170 before the template foo was processed.
2171
2172 A simple fix is to do any of the following:
2173
2174 [% PROCESS foo a = b FILTER html %]
2175
2176 [% | html %][% PROCESS foo a = b %][% END %]
2177
2178 [% FILTER html %][% PROCESS foo a = b %][% END %]
2179
2180 This shouldn't be too much hardship and offers the great return of disambiguating
2181 virtual method access.
2182
2183 =item C<\>
2184
2185 Unary. The reference operator. Not well publicized in TT. Stores a reference
2186 to a variable for use later. Can also be used to "alias" long names.
2187
2188 [% f = 7 ; foo = \f ; f = 8 ; foo %] => 8
2189
2190 [% foo = \f.g.h.i.j.k; f.g.h.i.j.k = 7; foo %] => 7
2191
2192 [% f = "abcd"; foo = \f.replace("ab", "-AB-") ; foo %] => -AB-cd
2193
2194 [% f = "abcd"; foo = \f.replace("bc") ; foo("-BC-") %] => a-BC-d
2195
2196 [% f = "abcd"; foo = \f.replace ; foo("cd", "-CD-") %] => ab-CD-
2197
2198 =item C<++ -->
2199
2200 Pre and post increment and decrement. My be used as either a prefix
2201 or postfix operator.
2202
2203 [% ++a %][% ++a %] => 12
2204
2205 [% a++ %][% a++ %] => 01
2206
2207 [% --a %][% --a %] => -1-2
2208
2209 [% a-- %][% a-- %] => 0-1
2210
2211 =item C<** ^ pow>
2212
2213 Right associative binary. X raised to the Y power. This isn't available in TT 2.15.
2214
2215 [% 2 ** 3 %] => 8
2216
2217 =item C<!>
2218
2219 Prefix not. Negation of the value.
2220
2221 =item C<->
2222
2223 Prefix minus. Returns the value multiplied by -1.
2224
2225 [% a = 1 ; b = -a ; b %] => -1
2226
2227 =item C<*>
2228
2229 Left associative binary. Multiplication.
2230
2231 =item C</ div DIV>
2232
2233 Left associative binary. Division. Note that / is floating point division, but div and
2234 DIV are integer division.
2235
2236 [% 10 / 4 %] => 2.5
2237 [% 10 div 4 %] => 2
2238
2239 =item C<% mod MOD>
2240
2241 Left associative binary. Modulus.
2242
2243 [% 15 % 8 %] => 7
2244
2245 =item C<+>
2246
2247 Left associative binary. Addition.
2248
2249 =item C<->
2250
2251 Left associative binary. Minus.
2252
2253 =item C<_ ~>
2254
2255 Left associative binary. String concatenation.
2256
2257 [% "a" ~ "b" %] => ab
2258
2259 =item C<< < > <= >= >>
2260
2261 Non associative binary. Numerical comparators.
2262
2263 =item C<lt gt le ge>
2264
2265 Non associative binary. String comparators.
2266
2267 =item C<== eq>
2268
2269 Non associative binary. Equality test. TT chose to use Perl's eq for both operators.
2270 There is no test for numeric equality.
2271
2272 =item C<!= ne>
2273
2274 Non associative binary. Non-equality test. TT chose to use Perl's ne for both
2275 operators. There is no test for numeric non-equality.
2276
2277 =item C<&&>
2278
2279 Left associative binary. And. All values must be true. If all values are true, the last
2280 value is returned as the truth value.
2281
2282 [% 2 && 3 && 4 %] => 4
2283
2284 =item C<||>
2285
2286 Right associative binary. Or. The first true value is returned.
2287
2288 [% 0 || '' || 7 %] => 7
2289
2290 Note: perl is left associative on this operator - but it doesn't matter because
2291 || has its own precedence level. Setting it to right allows for CET to short
2292 circuit earlier in the expression optree (left is (((1,2), 3), 4) while right
2293 is (1, (2, (3, 4))).
2294
2295 =item C<..>
2296
2297 Non associative binary. Range creator. Returns an arrayref containing the values
2298 between and including the first and last arguments.
2299
2300 [% t = [1 .. 5] %] => variable t contains an array with 1,2,3,4, and 5
2301
2302 It is possible to place multiple ranges in the same [] constructor. This is not available in TT.
2303
2304 [% t = [1..3, 6..8] %] => variable t contains an array with 1,2,3,6,7,8
2305
2306 The .. operator is the only operator that returns a list of items.
2307
2308 =item C<? :>
2309
2310 Ternary - right associative. Can be nested with other ?: pairs.
2311
2312 [% 1 ? 2 : 3 %] => 2
2313 [% 0 ? 2 : 3 %] => 3
2314
2315 =item C<*= += -= /= **= %= ~=>
2316
2317 Self-modifying assignment - right associative. Sets the left hand side
2318 to the operation of the left hand side and right (clear as mud).
2319 In order to not conflict with SET, FOREACH and other operations, this
2320 operator is only available in parenthesis.
2321
2322 [% a = 2 %][% a += 3 %] --- [% a %] => --- 5 # is handled by SET
2323 [% a = 2 %][% (a += 3) %] --- [% a %] => 5 --- 5
2324
2325 =item C<=>
2326
2327 Assignment - right associative. Sets the left-hand side to the value of the righthand side. In order
2328 to not conflict with SET, FOREACH and other operations, this operator is only
2329 available in parenthesis. Returns the value of the righthand side.
2330
2331 [% a = 1 %] --- [% a %] => --- 1 # is handled by SET
2332 [% (a = 1) %] --- [% a %] => 1 --- 1
2333
2334 =item C<not NOT>
2335
2336 Prefix. Lower precedence version of the '!' operator.
2337
2338 =item C<and AND>
2339
2340 Left associative. Lower precedence version of the '&&' operator.
2341
2342 =item C<or OR>
2343
2344 Right associative. Lower precedence version of the '||' operator.
2345
2346 =item C<{}>
2347
2348 This operator is not used in TT. It is used internally
2349 by CGI::Ex::Template to delay the creation of a hash until the
2350 execution of the compiled template.
2351
2352 =item C<[]>
2353
2354 This operator is not used in TT. It is used internally
2355 by CGI::Ex::Template to delay the creation of an array until the
2356 execution of the compiled template.
2357
2358 =item C<qr>
2359
2360 This operator is not used in TT. It is used internally
2361 by CGI::Ex::Template to store a regular expression and its options.
2362 It will return a compiled Regexp object when compiled.
2363
2364 =back
2365
2366
2367 =head1 CHOMPING
2368
2369 Chomping refers to the handling of whitespace immediately before and
2370 immediately after template tags. By default, nothing happens to this
2371 whitespace. Modifiers can be placed just inside the opening and just
2372 before the closing tags to control this behavior.
2373
2374 Additionally, the PRE_CHOMP and POST_CHOMP configuration variables can
2375 be set and will globally control all chomping behavior for tags that
2376 do not have their own chomp modifier. PRE_CHOMP and POST_CHOMP can
2377 be set to any of the following values:
2378
2379 none: 0 + Template::Constants::CHOMP_NONE
2380 one: 1 - Template::Constants::CHOMP_ONE
2381 collapse: 2 = Template::Constants::CHOMP_COLLAPSE
2382 greedy: 3 ~ Template::Constants::CHOMP_GREEDY
2383
2384 =over 4
2385
2386 =item CHOMP_NONE
2387
2388 Don't do any chomping. The "+" sign is used to indicate CHOMP_NONE.
2389
2390 Hello.
2391
2392 [%+ "Hi." +%]
2393
2394 Howdy.
2395
2396 Would print:
2397
2398 Hello.
2399
2400 Hi.
2401
2402 Howdy.
2403
2404 =item CHOMP_ONE (formerly known as CHOMP_ALL)
2405
2406 Delete any whitespace up to the adjacent newline. The "-" is used to indicate CHOMP_ONE.
2407
2408 Hello.
2409
2410 [%- "Hi." -%]
2411
2412 Howdy.
2413
2414 Would print:
2415
2416 Hello.
2417 Hi.
2418 Howdy.
2419
2420 =item CHOMP_COLLAPSE
2421
2422 Collapse adjacent whitespace to a single space. The "=" is used to indicate CHOMP_COLLAPSE.
2423
2424 Hello.
2425
2426 [%= "Hi." =%]
2427
2428 Howdy.
2429
2430 Would print:
2431
2432 Hello. Hi. Howdy.
2433
2434 =item CHOMP_GREEDY
2435
2436 Remove all adjacent whitespace. The "~" is used to indicate CHOMP_GREEDY.
2437
2438 Hello.
2439
2440 [%~ "Hi." ~%]
2441
2442 Howdy.
2443
2444 Would print:
2445
2446 Hello.Hi.Howdy.
2447
2448 =head1 CONFIGURATION
2449
2450 The following TT2 configuration variables are supported (in
2451 alphabetical order). Note: for further discussion you can refer to
2452 the TT config documentation.
2453
2454 These variables should be passed to the "new" constructor.
2455
2456 my $obj = CGI::Ex::Template->new(
2457 VARIABLES => \%hash_of_variables,
2458 AUTO_RESET => 0,
2459 TRIM => 1,
2460 POST_CHOMP => "=",
2461 PRE_CHOMP => "-",
2462 );
2463
2464
2465 =over 4
2466
2467 =item ABSOLUTE
2468
2469 Boolean. Default false. Are absolute paths allowed for included files.
2470
2471 =item ANYCASE
2472
2473 Allow directive matching to be case insensitive.
2474
2475 [% get 23 %] prints 23 with ANYCASE => 1
2476
2477 =item AUTO_RESET
2478
2479 Boolean. Default 1. Clear blocks that were set during the process method.
2480
2481 =item BLOCKS
2482
2483 A hashref of blocks that can be used by the process method.
2484
2485 BLOCKS => {
2486 block_1 => sub { ... }, # coderef that returns a block
2487 block_2 => 'A String', # simple string
2488 },
2489
2490 Note that a Template::Document cannot be supplied as a value (TT
2491 supports this). However, it is possible to supply a value that is
2492 equal to the hashref returned by the load_parsed_tree method.
2493
2494 =item CACHE_SIZE
2495
2496 Number of compiled templates to keep in memory. Default undef.
2497 Undefined means to allow all templates to cache. A value of 0 will
2498 force no caching. The cache mechanism will clear templates that have
2499 not been used recently.
2500
2501 =item COMPILE_DIR
2502
2503 Base directory to store compiled templates. Default undef. Compiled
2504 templates will only be stored if one of COMPILE_DIR and COMPILE_EXT is
2505 set.
2506
2507 =item COMPILE_EXT
2508
2509 Extension to add to stored compiled template filenames. Default undef.
2510
2511 =item CONSTANTS
2512
2513 Hashref. Used to define variables that will be "folded" into the
2514 compiled template. Variables defined here cannot be overridden.
2515
2516 CONSTANTS => {my_constant => 42},
2517
2518 A template containing:
2519
2520 [% constants.my_constant %]
2521
2522 Will have the value 42 compiled in.
2523
2524 Constants defined in this way can be chained as in [%
2525 constant.foo.bar.baz %].
2526
2527 =item CONSTANT_NAMESPACE
2528
2529 Allow for setting the top level of values passed in CONSTANTS. Default
2530 value is 'constants'.
2531
2532 =item DEBUG
2533
2534 Takes a list of constants |'ed together which enables different
2535 debugging modes. Alternately the lowercase names may be used
2536 (multiple values joined by a ",").
2537
2538 The only supported TT values are:
2539 DEBUG_UNDEF (2) - debug when an undefined value is used.
2540 DEBUG_DIRS (8) - debug when a directive is used.
2541 DEBUG_ALL (2047) - turn on all debugging.
2542
2543 Either of the following would turn on undef and directive debugging:
2544
2545 DEBUG => 'undef, dirs', # preferred
2546 DEBUG => 2 | 8,
2547 DEBUG => DEBUG_UNDEF | DEBUG_DIRS, # constants from Template::Constants
2548
2549 =item DEBUG_FORMAT
2550
2551 Change the format of messages inserted when DEBUG has DEBUG_DIRS set on.
2552 This essentially the same thing as setting the format using the DEBUG
2553 directive.
2554
2555 =item DEFAULT
2556
2557 The name of a default template file to use if the passed one is not found.
2558
2559 =item DELIMITER
2560
2561 String to use to split INCLUDE_PATH with. Default is :. It is more
2562 straight forward to just send INCLUDE_PATH an arrayref of paths.
2563
2564 =item DUMP
2565
2566 Configures the behavior of the DUMP tag. May be set to 0, a hashref,
2567 or another true value. Default is true.
2568
2569 If set to 0, all DUMP directives will do nothing. This is useful if
2570 you would like to turn off the DUMP directives under some environments.
2571
2572 IF set to a true value (or undefined) then DUMP directives will operate.
2573
2574 If set to a hashref, the values of the hash can be used to configure
2575 the operation of the DUMP directives. The following are the values
2576 that can be set in this hash.
2577
2578 =over 4
2579
2580 =item EntireStash
2581
2582 Default 1. If set to 0, then the DUMP directive will not print the
2583 entire contents of the stash when a DUMP directive is called without
2584 arguments.
2585
2586 =item handler
2587
2588 Defaults to an internal coderef. If set to a coderef, the DUMP directive will pass the
2589 arguments to be dumped and expects a string with the dumped data. This
2590 gives complete control over the dump process.
2591
2592 Note 1: The default handler makes sure that values matching the
2593 private variable regex are not included. If you install your own handler,
2594 you will need to take care of these variables if you intend for them
2595 to not be shown.
2596
2597 Note 2: If you would like the name of the variable to be dumped, include
2598 the string '$VAR1' and the DUMP directive will interpolate the value. For
2599 example, to dump all output as YAML - you could do the following:
2600
2601 DUMP => {
2602 handler => sub {
2603 require YAML;
2604 return "\$VAR1 =\n".YAML::Dump(shift);
2605 },
2606 }
2607
2608 =item header
2609
2610 Default 1. Controls whether a header is printed for each DUMP directive.
2611 The header contains the file and line number the DUMP directive was
2612 called from. If set to 0 the headers are disabled.
2613
2614 =item html
2615
2616 Defaults to 1 if $ENV{'REQUEST_METHOD'} is set - 0 otherwise. If set to
2617 1, then the output of the DUMP directive is passed to the html filter
2618 and encased in "pre" tags. If set to 0 no html encoding takes place.
2619
2620 =item Sortkeys, Useqq, Ident, Pad, etc
2621
2622 Any of the Data::Dumper configuration items may be passed.
2623
2624 =back
2625
2626 =item END_TAG
2627
2628 Set a string to use as the closing delimiter for TT. Default is "%]".
2629
2630 =item ERROR
2631
2632 Used as a fall back when the processing of a template fails. May either
2633 be a single filename that will be used in all cases, or may be a hashref
2634 of options where the keynames represent error types that will be handled
2635 by the filename in their value. A key named default will be used if no
2636 other matching keyname can be found. The selection process is similar
2637 to that of the TRY/CATCH/THROW directives (see those directives for more
2638 information).
2639
2640 my $t = CGI::Ex::Template->new({
2641 ERROR => 'general/catch_all_errors.html',
2642 });
2643
2644 my $t = CGI::Ex::Template->new({
2645 ERROR => {
2646 default => 'general/catch_all_errors.html',
2647 foo => 'catch_all_general_foo_errors.html',
2648 'foo.bar' => 'catch_foo_bar_errors.html',
2649 },
2650 });
2651
2652 Note that the ERROR handler will only be used for errors during the
2653 processing of the main document. It will not catch errors that
2654 occur in templates found in the PRE_PROCESS, POST_PROCESS, and WRAPPER
2655 configuration items.
2656
2657 =item ERRORS
2658
2659 Same as the ERROR configuration item. Both may be used interchangably.
2660
2661 =item EVAL_PERL
2662
2663 Boolean. Default false. If set to a true value, PERL and RAWPERL blocks
2664 will be allowed to run. This is a potential security hole, as arbitrary
2665 perl can be included in the template. If Template::Toolkit is installed,
2666 a true EVAL_PERL value also allows the perl and evalperl filters to be used.
2667
2668 =item FILTERS
2669
2670 Allow for passing in TT style filters.
2671
2672 my $filters = {
2673 filter1 => sub { my $str = shift; $s =~ s/./1/gs; $s },
2674 filter2 => [sub { my $str = shift; $s =~ s/./2/gs; $s }, 0],
2675 filter3 => [sub { my ($context, @args) = @_; return sub { my $s = shift; $s =~ s/./3/gs; $s } }, 1],
2676 };
2677
2678 my $str = q{
2679 [% a = "Hello" %]
2680 1 ([% a | filter1 %])
2681 2 ([% a | filter2 %])
2682 3 ([% a | filter3 %])
2683 };
2684
2685 my $obj = CGI::Ex::Template->new(FILTERS => $filters);
2686 $obj->process(\$str) || die $obj->error;
2687
2688 Would print:
2689
2690 1 (11111)
2691 2 (22222)
2692 3 (33333)
2693
2694 Filters passed in as an arrayref should contain a coderef and a value
2695 indicating if they are dynamic or static (true meaning dynamic). The
2696 dynamic filters are passed the pseudo context object and any arguments
2697 and should return a coderef that will be called as the filter. The filter
2698 coderef is then passed the string.
2699
2700 =item INCLUDE_PATH
2701
2702 A string or an arrayref or coderef that returns an arrayref that
2703 contains directories to look for files included by processed
2704 templates.
2705
2706 =item INCLUDE_PATHS
2707
2708 Non-TT item. Same as INCLUDE_PATH but only takes an arrayref. If not specified
2709 then INCLUDE_PATH is turned into an arrayref and stored in INCLUDE_PATHS.
2710 Overrides INCLUDE_PATH.
2711
2712 =item INTERPOLATE
2713
2714 Boolean. Specifies whether variables in text portions of the template will be
2715 interpolated. For example, the $variable and ${var.value} would be substituted
2716 with the appropriate values from the variable cache (if INTERPOLATE is on).
2717
2718 [% IF 1 %]The variable $variable had a value ${var.value}[% END %]
2719
2720 =item LOAD_PERL
2721
2722 Indicates if the USE directive can fall back and try and load a perl module
2723 if the indicated module was not found in the PLUGIN_BASE path. See the
2724 USE directive.
2725
2726 =item MAX_EVAL_RECURSE (CET only)
2727
2728 Will use $CGI::Ex::Template::MAX_EVAL_RECURSE if not present. Default is 50.
2729 Prevents runaway on the following:
2730
2731 [% f = "[% f|eval %]" %][% f|eval %]
2732
2733 =item MAX_MACRO_RECURSE (CET only)
2734
2735 Will use $CGI::Ex::Template::MAX_MACRO_RECURSE if not present. Default is 50.
2736 Prevents runaway on the following:
2737
2738 [% MACRO f BLOCK %][% f %][% END %][% f %]
2739
2740 =item NAMESPACE
2741
2742 No Template::Namespace::Constants support. Hashref of hashrefs representing
2743 constants that will be folded into the template at compile time.
2744
2745 CGI::Ex::Template->new(NAMESPACE => {constants => {
2746 foo => 'bar',
2747 }});
2748
2749 Is the same as
2750
2751 CGI::Ex::Template->new(CONSTANTS => {
2752 foo => 'bar',
2753 });
2754
2755 Any number of hashes can be added to the NAMESPACE hash.
2756
2757 =item NEGATIVE_STAT_TTL (Not in TT)
2758
2759 Defaults to STAT_TTL which defaults to $STAT_TTL which defaults to 1.
2760
2761 Similar to STAT_TTL - but represents the time-to-live
2762 seconds until a document that was not found is checked again against
2763 the system for modifications. Setting this number higher will allow for
2764 fewer file system accesses. Setting it to a negative number will allow
2765 for the file system to be checked every hit.
2766
2767 =item OUTPUT
2768
2769 Alternate way of passing in the output location for processed templates.
2770 If process is not passed an output argument, it will look for this value.
2771
2772 See the process method for a listing of possible values.
2773
2774 =item OUTPUT_PATH
2775
2776 Base path for files written out via the process method or via the redirect
2777 and file filters. See the redirect virtual method and the process method
2778 for more information.
2779
2780 =item PLUGINS
2781
2782 A hashref of mappings of plugin modules.
2783
2784 PLUGINS => {
2785 Iterator => 'Template::Plugin::Iterator',
2786 DBI => 'MyDBI',
2787 },
2788
2789 See the USE directive for more information.
2790
2791 =item PLUGIN_BASE
2792
2793 Default value is Template::Plugin. The base module namespace
2794 that template plugins will be looked for. See the USE directive
2795 for more information. May be either a single namespace, or an arrayref
2796 of namespaces.
2797
2798 =item POST_CHOMP
2799
2800 Set the type of chomping at the ending of a tag.
2801 See the section on chomping for more information.
2802
2803 =item POST_PROCESS
2804
2805 A list of templates to be processed and appended to the content
2806 after the main template. During this processing the "template"
2807 namespace will contain the name of the main file being processed.
2808
2809 This is useful for adding a global footer to all templates.
2810
2811 =item PRE_CHOMP
2812
2813 Set the type of chomping at the beginning of a tag.
2814 See the section on chomping for more information.
2815
2816 =item PRE_DEFINE
2817
2818 Same as the VARIABLES configuration item.
2819
2820 =item PRE_PROCESS
2821
2822 A list of templates to be processed before and pre-pended to the content
2823 before the main template. During this processing the "template"
2824 namespace will contain the name of the main file being processed.
2825
2826 This is useful for adding a global header to all templates.
2827
2828 =item PROCESS
2829
2830 Specify a file to use as the template rather than the one passed in
2831 to the ->process method.
2832
2833 =item RECURSION
2834
2835 Boolean. Default false. Indicates that INCLUDED or PROCESSED files
2836 can refer to each other in a circular manner. Be careful about recursion.
2837
2838 =item RELATIVE
2839
2840 Boolean. Default false. If true, allows filenames to be specified
2841 that are relative to the currently running process.
2842
2843 =item START_TAG
2844
2845 Set a string to use as the opening delimiter for TT. Default is "[%".
2846
2847 =item STAT_TTL
2848
2849 Defaults to $STAT_TTL which defaults to 1. Represents time-to-live
2850 seconds until a cached in memory document is compared to the file
2851 system for modifications. Setting this number higher will allow for
2852 fewer file system accesses. Setting it to a negative number will allow
2853 for the file system to be checked every hit.
2854
2855 =item TAG_STYLE
2856
2857 Allow for setting the type of tag delimiters to use for parsing the TT.
2858 See the TAGS directive for a listing of the available types.
2859
2860 =item TRIM
2861
2862 Remove leading and trailing whitespace from blocks and templates.
2863 This operation is performed after all enclosed template tags have
2864 been executed.
2865
2866 =item UNDEFINED_ANY
2867
2868 This is not a TT configuration option. This option expects to be a code
2869 ref that will be called if a variable is undefined during a call to play_expr.
2870 It is passed the variable identity array as a single argument. This
2871 is most similar to the "undefined" method of Template::Stash. It allows
2872 for the "auto-defining" of a variable for use in the template. It is
2873 suggested that UNDEFINED_GET be used instead as UNDEFINED_ANY is a little
2874 to general in defining variables.
2875
2876 You can also sub class the module and override the undefined_any method.
2877
2878 =item UNDEFINED_GET
2879
2880 This is not a TT configuration option. This option expects to be a code
2881 ref that will be called if a variable is undefined during a call to GET.
2882 It is passed the variable identity array as a single argument. This is more useful
2883 than UNDEFINED_ANY in that it is only called during a GET directive
2884 rather than in embedded expressions (such as [% a || b || c %]).
2885
2886 You can also sub class the module and override the undefined_get method.
2887
2888 =item V1DOLLAR
2889
2890 This allows for some compatibility with TT1 templates. The only real
2891 behavior change is that [% $foo %] becomes the same as [% foo %]. The
2892 following is a basic table of changes invoked by using V1DOLLAR.
2893
2894 With V1DOLLAR Equivalent Without V1DOLLAR (Normal default)
2895 "[% foo %]" "[% foo %]"
2896 "[% $foo %]" "[% foo %]"
2897 "[% ${foo} %]" "[% ${foo} %]"
2898 "[% foo.$bar %]" "[% foo.bar %]"
2899 "[% ${foo.bar} %]" "[% ${foo.bar} %]"
2900 "[% ${foo.$bar} %]" "[% ${foo.bar} %]"
2901 "Text: $foo" "Text: $foo"
2902 "Text: ${foo}" "Text: ${foo}"
2903 "Text: ${$foo}" "Text: ${foo}"
2904
2905 =item V2PIPE
2906
2907 Restores the behavior of the pipe operator to be compatible with TT2.
2908
2909 With V2PIPE = 1
2910
2911 [%- BLOCK a %]b is [% b %]
2912 [% END %]
2913 [%- PROCESS a b => 237 | repeat(2) %]
2914
2915 # output of block "a" with b set to 237 is passed to the repeat(2) filter
2916
2917 b is 237
2918 b is 237
2919
2920 With V2PIPE = 0 (default)
2921
2922 [%- BLOCK a %]b is [% b %]
2923 [% END %]
2924 [% PROCESS a b => 237 | repeat(2) %]
2925
2926 # b set to 237 repeated twice, and b passed to block "a"
2927
2928 b is 237237
2929
2930 =item VARIABLES
2931
2932 A hashref of variables to initialize the template stash with. These
2933 variables are available for use in any of the executed templates.
2934 See the section on VARIABLES for the types of information that can be passed in.
2935
2936 =item WRAPPER
2937
2938 Operates similar to the WRAPPER directive. The option can be given a
2939 single filename, or an arrayref of filenames that will be used to wrap
2940 the processed content. If an arrayref is passed the filenames are
2941 processed in reverse order, so that the first filename specified will
2942 end up being on the outside (surrounding all other wrappers).
2943
2944 my $t = CGI::Ex::Template->new(
2945 WRAPPER => ['my/wrappers/outer.html', 'my/wrappers/inner.html'],
2946 );
2947
2948 Content generated by the PRE_PROCESS and POST_PROCESS will come before
2949 and after (respectively) the content generated by the WRAPPER
2950 configuration item.
2951
2952 See the WRAPPER direcive for more examples of how wrappers are construted.
2953
2954 =back
2955
2956
2957 =head1 UNSUPPORTED TT CONFIGURATION
2958
2959 =over 4
2960
2961 =item LOAD_TEMPLATES
2962
2963 CGI::Ex::Template has its own mechanism for loading and storing
2964 compiled templates. TT would use a Template::Provider that would
2965 return a Template::Document. The closest thing in CGI::Ex::Template
2966 is the load_parsed_template method. There is no immediate plan to
2967 support the TT behavior.
2968
2969 =item LOAD_PLUGINS
2970
2971 CGI::Ex::Template uses its own mechanism for loading plugins. TT
2972 would use a Template::Plugins object to load plugins requested via the
2973 USE directive. The functionality for doing this in CGI::Ex::Template
2974 is contained in the list_plugins method and the play_USE method. There
2975 is no immediate plan to support the TT behavior.
2976
2977 Full support is offered for the PLUGINS and LOAD_PERL configuration items.
2978
2979 Also note that CGI::Ex::Template only natively supports the Iterator plugin.
2980 Any of the other plugins requested will need to provided by installing
2981 Template::Toolkit or the appropriate plugin module.
2982
2983 =item LOAD_FILTERS
2984
2985 CGI::Ex::Template uses its own mechanism for loading filters. TT
2986 would use the Template::Filters object to load filters requested via the
2987 FILTER directive. The functionality for doing this in CGI::Ex::Template
2988 is contained in the list_filters method and the play_expr method.
2989
2990 Full support is offered for the FILTERS configuration item.
2991
2992 =item TOLERANT
2993
2994 This option is used by the LOAD_TEMPLATES and LOAD_PLUGINS options and
2995 is not applicable in CGI::Ex::Template.
2996
2997 =item SERVICE
2998
2999 CGI::Ex::Template has no concept of service (theoretically the CGI::Ex::Template
3000 is the "service").
3001
3002 =item CONTEXT
3003
3004 CGI::Ex::Template provides its own pseudo context object to plugins,
3005 filters, and perl blocks. The CGI::Ex::Template model doesn't really
3006 allow for a separate context. CGI::Ex::Template IS the context.
3007
3008 =item STASH
3009
3010 CGI::Ex::Template manages its own stash of variables. A pseudo stash
3011 object is available via the pseudo context object for use in plugins,
3012 filters, and perl blocks.
3013
3014 =item PARSER
3015
3016 CGI::Ex::Template has its own built in parser. The closest similarity is
3017 the parse_tree method. The output of parse_tree is an optree that is
3018 later run by execute_tree. CET provides a backend to the Template::Parser::CET
3019 module which can be used to replace the default parser when using
3020 the standard Template::Toolkit library.
3021
3022 =item GRAMMAR
3023
3024 CGI::Ex::Template maintains its own grammar. The grammar is defined
3025 in the parse_tree method and the callbacks listed in the global
3026 $DIRECTIVES hashref.
3027
3028 =back
3029
3030
3031 =head1 VARIABLE PARSE TREE
3032
3033 CGI::Ex::Template parses templates into an tree of operations (an AST
3034 or abstract syntax tree). Even variable access is parsed into a tree.
3035 This is done in a manner somewhat similar to the way that TT operates
3036 except that nested variables such as foo.bar|baz contain the '.' or
3037 '|' in between each name level. Operators are parsed and stored as
3038 part of the variable (it may be more appropriate to say we are parsing
3039 a term or an expression).
3040
3041 The following table shows a variable or expression and the corresponding parsed tree
3042 (this is what the parse_expr method would return).
3043
3044 one [ 'one', 0 ]
3045 one() [ 'one', [] ]
3046 one.two [ 'one', 0, '.', 'two', 0 ]
3047 one|two [ 'one', 0, '|', 'two', 0 ]
3048 one.$two [ 'one', 0, '.', ['two', 0 ], 0 ]
3049 one(two) [ 'one', [ ['two', 0] ] ]
3050 one.${two().three} [ 'one', 0, '.', ['two', [], '.', 'three', 0], 0]
3051 2.34 2.34
3052 "one" "one"
3053 1 + 2 [ [ undef, '+', 1, 2 ], 0]
3054 a + b [ [ undef, '+', ['a', 0], ['b', 0] ], 0 ]
3055 "one"|length [ [ undef, '~', "one" ], 0, '|', 'length', 0 ]
3056 "one $a two" [ [ undef, '~', 'one ', ['a', 0], ' two' ], 0 ]
3057 [0, 1, 2] [ [ undef, '[]', 0, 1, 2 ], 0 ]
3058 [0, 1, 2].size [ [ undef, '[]', 0, 1, 2 ], 0, '.', 'size', 0 ]
3059 ['a', a, $a ] [ [ undef, '[]', 'a', ['a', 0], [['a', 0], 0] ], 0]
3060 {a => 'b'} [ [ undef, '{}', 'a', 'b' ], 0 ]
3061 {a => 'b'}.size [ [ undef, '{}', 'a', 'b' ], 0, '.', 'size', 0 ]
3062 {$a => b} [ [ undef, '{}', ['a', 0], ['b', 0] ], 0 ]
3063 a * (b + c) [ [ undef, '*', ['a', 0], [ [undef, '+', ['b', 0], ['c', 0]], 0 ]], 0 ]
3064 (a + b) [ [ undef, '+', ['a', 0], ['b', 0] ]], 0 ]
3065 (a + b) * c [ [ undef, '*', [ [undef, '+', ['a', 0], ['b', 0] ], 0 ], ['c', 0] ], 0 ]
3066 a ? b : c [ [ undef, '?', ['a', 0], ['b', 0], ['c', 0] ], 0 ]
3067 a || b || c [ [ undef, '||', ['a', 0], [ [undef, '||', ['b', 0], ['c', 0] ], 0 ] ], 0 ]
3068 ! a [ [ undef, '!', ['a', 0] ], 0 ]
3069
3070 Some notes on the parsing.
3071
3072 Operators are parsed as part of the variable and become part of the variable tree.
3073
3074 Operators are stored in the variable tree using an operator identity array which
3075 contains undef as the first value, the operator, and the operator arguments. This
3076 allows for quickly descending the parsed variable tree and determining that the next
3077 node is an operator.
3078
3079 Parenthesis () can be used at any point in an expression to disambiguate precedence.
3080
3081 "Variables" that appear to be literal strings or literal numbers
3082 are returned as the literal (no operator tree).
3083
3084 The following perl can be typed at the command line to view the parsed variable tree:
3085
3086 perl -e 'use CGI::Ex::Template; print CGI::Ex::Template::dump_parse_expr("foo.bar + 2")."\n"'
3087
3088 Also the following can be included in a template to view the output in a template:
3089
3090 [% USE cet = CGI::Ex::Template %]
3091 [%~ cet.dump_parse_expr('foo.bar + 2').replace('\s+', ' ') %]
3092
3093
3094 =head1 SEMI PUBLIC METHODS
3095
3096 The following list of methods are other interesting methods of CET that
3097 may be re-implemented by subclasses of CET.
3098
3099 =over 4
3100
3101 =item C<dump_parse>
3102
3103 This method allows for returning a Data::Dumper dump of a parsed
3104 template. It is mainly used for testing.
3105
3106 =item C<dump_parse_expr>
3107
3108 This method allows for returning a Data::Dumper dump of a parsed
3109 variable. It is mainly used for testing.
3110
3111 =item C<exception>
3112
3113 Creates an exception object blessed into the package listed in
3114 $CGI::Ex::Template::PACKAGE_EXCEPTION.
3115
3116 =item C<execute_tree>
3117
3118 Executes a parsed tree (returned from parse_tree)
3119
3120 =item C<play_expr>
3121
3122 Play the parsed expression. Turns a variable identity array into the
3123 parsed variable. This method is also responsible for playing
3124 operators and running virtual methods and filters. The variable
3125 identity array may also contain literal values, or operator identity
3126 arrays.
3127
3128 =item C<include_filename>
3129
3130 Takes a file path, and resolves it into the full filename using
3131 paths from INCLUDE_PATH or INCLUDE_PATHS.
3132
3133 =item C<_insert>
3134
3135 Resolves the file passed, and then returns its contents.
3136
3137 =item C<list_filters>
3138
3139 Dynamically loads the filters list from Template::Filters when a filter
3140 is used that is not natively implemented in CET.
3141
3142 =item C<list_plugins>
3143
3144 Returns an arrayref of modules that are under a base Namespace.
3145
3146 my @modules = @{ $self->list_plugins({base => 'Template::Plugins'}) }:
3147
3148 =item C<load_parsed_tree>
3149
3150 Given a filename or a string reference will return a parsed document
3151 hash that contains the parsed tree.
3152
3153 my $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");
3154
3155 =item C<parse_args>
3156
3157 Allow for the multitudinous ways that TT parses arguments. This allows
3158 for positional as well as named arguments. Named arguments can be separated with a "=" or "=>",
3159 and positional arguments should be separated by " " or ",". This only returns an array
3160 of parsed variables. To get the actual values, you must call play_expr on each value.
3161
3162 =item C<parse_tree>
3163
3164 Used by load_parsed_tree. This is the main grammar engine of the program. It
3165 uses method in the $DIRECTIVES hashref to parse different DIRECTIVE TYPES.
3166
3167 =item C<parse_expr>
3168
3169 Used to parse a variable, an expression, a literal string, or a number. It
3170 returns a parsed variable tree. Samples of parsed variables can be found in the VARIABLE PARSE TREE
3171 section.
3172
3173 =item C<set_variable>
3174
3175 Used to set a variable. Expects a variable identity array and the value to set. It
3176 will autovifiy as necessary.
3177
3178 =item C<throw>
3179
3180 Creates an exception object from the arguments and dies.
3181
3182 =item C<undefined_any>
3183
3184 Called during play_expr if a value is returned that is undefined. This could
3185 be used to magically create variables on the fly. This is similar to Template::Stash::undefined.
3186 It is suggested that undefined_get be used instead. Default behavior returns undef. You
3187 may also pass a coderef via the UNDEFINED_ANY configuration variable. Also, you can try using
3188 the DEBUG => 'undef', configuration option which will throw an error on undefined variables.
3189
3190 =item C<undefined_get>
3191
3192 Called when a variable is undefined during a GET directive. This is useful to
3193 see if a value that is about to get inserted into the text is undefined. undefined_any is a little
3194 too general for most cases. Also, you may pass a coderef via the UNDEFINED_GET configuration variable.
3195
3196 =back
3197
3198
3199 =head1 OTHER UTILITY METHODS
3200
3201 The following is a brief list of other methods used by CET. Generally, these
3202 shouldn't be overwritten by subclasses.
3203
3204 =over 4
3205
3206 =item C<apply_precedence>
3207
3208 Allows for parsed operator array to be translated to a tree based
3209 upon operator precedence.
3210
3211 =item C<context>
3212
3213 Used to create a "pseudo" context object that allows for portability
3214 of TT plugins, filters, and perl blocks that need a context object.
3215
3216 =item C<DEBUG>
3217
3218 TT2 Holdover that is used once for binmode setting during a TT2 test.
3219
3220 =item C<debug_node>
3221
3222 Used to get debug info on a directive if DEBUG_DIRS is set.
3223
3224 =item C<filter_*>
3225
3226 Methods by these names implement filters that are more complex than one liners.
3227
3228 =item C<get_line_number_by_index>
3229
3230 Used to turn string index position into line number
3231
3232 =item C<interpolate_node>
3233
3234 Used for parsing text nodes for dollar variables when interpolate is on.
3235
3236 =item C<parse_*>
3237
3238 Methods by these names are used by parse_tree to parse the template. These are the grammar.
3239
3240 =item C<play_*>
3241
3242 Methods by these names are used by execute_tree to execute the parsed tree.
3243
3244 =item C<play_operator>
3245
3246 Used to execute any found operators. The single argument is
3247 an operator identy returned by the parse_expr method (if the expression
3248 contained an operator). Normally you would just call play_expr
3249 instead and it will call play_operator if the structure
3250 contains an operator.
3251
3252 =item C<_process>
3253
3254 Called by process and the PROCESS, INCLUDE and other directives.
3255
3256 =item C<slurp>
3257
3258 Reads contents of passed filename - throws file exception on error.
3259
3260 =item C<split_paths>
3261
3262 Used to split INCLUDE_PATH or other directives if an arrayref is not passed.
3263
3264 =item C<_vars>
3265
3266 Return a reference to the current stash of variables. This is currently only used
3267 by the pseudo context object and may disappear at some point.
3268
3269 =item C<vmethod_*>
3270
3271 Methods by these names implement virtual methods that are more complex than oneliners.
3272
3273 =back
3274
3275
3276 =head1 AUTHOR
3277
3278 Paul Seamons <paul at seamons dot com>
3279
3280 =head1 LICENSE
3281
3282 This module may be distributed under the same terms as Perl itself.
3283
3284 =cut
This page took 0.159411 seconds and 3 git commands to generate.