]> Dogcows Code - chaz/p5-CGI-Ex/blob - lib/CGI/Ex/Template.pod
e0ea84279a47c1ebea6a2222d7291a873fd16927
[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 $t->process('my/template.tt', $swap)
19 || die $t->error;
20
21 ### Anything in the Template::Toolkit SYNOPSIS would fit here also
22
23 =head1 DESCRIPTION
24
25 CGI::Ex::Template happened by accident (accidentally on purpose). The
26 CGI::Ex::Template (CET hereafter) was originally a part of the CGI::Ex
27 suite that performed simple variable interpolation. It used TT2 style
28 variables in TT2 style tags "[% foo.bar %]". That was all the
29 original CGI::Ex::Template did. This was fine and dandy for a couple
30 of years. In winter of 2005-2006 CET was revamped to add a few
31 features. One thing led to another and soon CET provided for most of
32 the features of TT2 as well as some from TT3. CGI::Ex::Template is a
33 full-featured implementation of the Template::Toolkit language.
34
35 CGI::Ex::Template (CET hereafter) is smaller, faster, uses less memory
36 and less CPU than TT2. However, it is most likely less portable, less
37 extendable, and probably has many of the bugs that TT2 has already massaged
38 out from years of bug reports and patches from a very active community
39 and mailing list. CET does not have a vibrant community behind it. Fixes
40 applied to TT2 will take longer to get into CET, should they get in at all.
41 An attempt will be made to follow updates made to TT2 to keep the two
42 in sync at a language level. There already has been, and it is expected that
43 there will continue to be code sharing between the two projects. (Acutally
44 I will try and keep applicable fixes in sync with TT).
45
46 Most of the standard Template::Toolkit documentation covering directives,
47 variables, configuration, plugins, filters, syntax, and vmethods should
48 apply to CET just fine (This pod tries to explain everything - but there is
49 too much). The section on differences between CET and TT will explain
50 what too look out for.
51
52 Note: A clarification on "faster". All templates are going to take
53 different amounts of time to process. Different types of DIRECTIVES
54 parse and play more quickly than others. The test script
55 samples/benchmark/bench_template.pl was used to obtain sample numbers.
56 In general the following statements are true:
57
58 If you load a new Template object each time and pass a filename, CET
59 is around 4 times faster.
60
61 If you load a new Template object and pass a string ref, CET
62 is around 3.5 times faster.
63
64 If you load a new Template object and use CACHE_EXT, CET
65 is around 1.5 times faster.
66
67 If you use a cached object with a cached in memory template,
68 then CET is 50% faster.
69
70 If you use Template::Stash::XS with a cached in memory template,
71 then CET is about as fast.
72
73 Using TT with a compiled-in-memory template is only 33
74 faster than CET with a new object compiling each time.
75
76 It is pretty hard to beat the speed of XS stash with compiled in
77 memory templates. Many systems don't have access to those so
78 CET may make more sense. Hopefully as TT is revised, many of the CET
79 speed advantages can be incorporated so that the core TT is just as
80 fast or faster.
81
82 So should you use CGI::Ex::Template ? Well, try it out. It may
83 give you no visible improvement. Or it could.
84
85
86 =head1 PUBLIC METHODS
87
88 The following section lists most of the publicly available methods. Some less
89 commonly used public methods are listed later in this document.
90
91 =over 4
92
93 =item C<new>
94
95 my $obj = CGI::Ex::Template->new({
96 INCLUDE_PATH => ['/my/path/to/content', '/my/path/to/content2'],
97 });
98
99 Arguments may be passed as a hash or as a hashref. Returns a CGI::Ex::Template object.
100
101 There are currently no errors during CGI::Ex::Template object creation.
102
103 =item C<process>
104
105 This is the main method call for staring processing. Any errors that results in the
106 template being stopped processing will be stored and available via the ->error method.
107
108 Process takes three arguments.
109
110 $t->process($in, $swap, $out)
111 || die $t->error;
112
113 The $in argument can be any one of:
114
115 String containing the filename of the template to be processed. The filename should
116 be relative to INCLUDE_PATH. (See INCLUDE_PATH, ABSOLUTE, and RELATIVE configuration items).
117 In memory caching and file side caching are available for this type.
118
119 A reference to a scalar containing the contents of the template to be processed.
120
121 A coderef that will be called to return the contents of the template.
122
123 An open filehandle that will return the contents of the template when read.
124
125 The $swap argument should be hashref containing key value pairs that will be
126 available to variables swapped into the template. Values can be hashrefs, hashrefs
127 of hashrefs and so on, arrayrefs, arrayrefs of arrayrefs and so on, coderefs, objects,
128 and simple scalar values such as numbers and strings. See the section on variables.
129
130 The $out argument can be any one of:
131
132 undef - meaning to print the completed template to STDOUT.
133
134 String containing a filename. The completed template will be placed in the file.
135
136 A reference to a string. The contents will be appended to the scalar reference.
137
138 A coderef. The coderef will be called with the contents as a single argument.
139
140 An object that can run the method "print". The contents will be passed as
141 a single argument to print.
142
143 An arrayref. The contents will be pushed onto the array.
144
145 An open filehandle. The contents will be printed to the open handle.
146
147 Additionally - the $out argument can be configured using the OUTPUT configuration
148 item.
149
150 =item C<process_simple>
151
152 Similar to the process method but with the following restrictions:
153
154 The $in parameter is limited to a filename or a reference a string containing the contents.
155
156 The $out parameter may only be a reference to a scalar string that output will be appended to.
157
158 Additionally, the following configuration variables will be ignored: VARIABLES,
159 PRE_DEFINE, BLOCKS, PRE_PROCESS, PROCESS, POST_PROCESS, AUTO_RESET, OUTPUT.
160
161 =item C<error>
162
163 Should something go wrong during a "process" command, the error that occurred can
164 be retrieved via the error method.
165
166 $obj->process('somefile.html', {a => 'b'}, \$string_ref)
167 || die $obj->error;
168
169 =item C<define_vmethod>
170
171 This method is available for defining extra Virtual methods or filters. This method is similar
172 to Template::Stash::define_vmethod.
173
174 =back
175
176 =head1 TODO
177
178 Add WRAPPER config item
179
180 Add ERROR config item
181
182 =head1 HOW IS CGI::Ex::Template DIFFERENT
183
184 CET uses the same template syntax and configuration items
185 as TT2, but the internals of CET were written from scratch. In
186 addition to this, the following is a list of some of the ways that
187 configuration and syntax of CET different from that of TT.
188
189 =over 4
190
191 Numerical hash keys work [% a = {1 => 2} %]
192
193 Quoted hash key interpolation is fine [% a = {"$foo" => 1} %]
194
195 Multiple ranges in same constructor [% a = [1..10, 21..30] %]
196
197 Constructor types can call virtual methods
198
199 [% a = [1..10].reverse %]
200
201 [% "$foo".length %]
202
203 [% 123.length %] # = 3
204
205 [% 123.4.length %] # = 5
206
207 [% -123.4.length %] # = -5 ("." binds more tightly than "-")
208
209 [% (a ~ b).length %]
210
211 [% "hi".repeat(3) %]
212
213 [% {a => b}.size %]
214
215 Reserved names are less reserved
216
217 [% GET GET %] # gets the variable named "GET"
218
219 [% GET $GET %] # gets the variable who's name is stored in "GET"
220
221 Filters and SCALAR_OPS are interchangeable.
222
223 [% a | length %]
224
225 [% b . lower %]
226
227 Pipe "|" can be used anywhere dot "." can be and means to call
228 the virtual method.
229
230 [% a = {size => "foo"} %][% a.size %] # = foo
231
232 [% a = {size => "foo"} %][% a|size %] # = 1 (size of hash)
233
234 Pipe "|" and "." can be mixed.
235
236 [% "aa" | repeat(2) . length %] # = 4
237
238 Whitespace is less meaningful.
239
240 [% 2-1 %] # = 1 (fails in TT)
241
242 Added pow operator.
243
244 [% 2 ** 3 %] [% 2 pow 3 %] # = 8 8
245
246 FOREACH variables can be nested
247
248 [% FOREACH f.b = [1..10] ; f.b ; END %]
249
250 Note that nested variables are subject to scoping issues.
251 f.b will not be reset to its value before the FOREACH.
252
253 Post operative directives can be nested.
254
255 [% one IF two IF three %]
256
257 same as
258
259 [% IF three %][% IF two %][% one %][% END %][% END %]
260
261
262 [% a = [[1..3], [5..7]] %][% i FOREACH i = j FOREACH j = a %] # = 123567
263
264 CATCH blocks can be empty.
265
266 CET does not generate Perl code. It generates an "opcode" tree.
267
268 CET uses storable for its compiled templates. If EVAL_PERL is off,
269 CET will not eval_string on ANY piece of information.
270
271 There is no context. CET provides a context object that mimics the
272 Template::Context interface for use by some TT filters, eval perl
273 blocks, and plugins.
274
275 There is no stash. CET only supports the variables passed in
276 VARIABLES, PRE_DEFINE, and those passed to the process method. CET
277 provides a stash object that mimics the Template::Stash interface for
278 use by some TT filters, eval perl blocks, and plugins.
279
280 There is no provider. CET uses the load_parsed_tree method to get and
281 cache templates.
282
283 There is no grammar. CET has its own built in grammar system.
284
285 There is no VIEW directive.
286
287 There are no references. (There was in initial beta tests, but it was decided
288 to remove the little used feature).
289
290 The DEBUG directive only understands DEBUG_DIRS (8) and DEBUG_UNDEF (2).
291
292 When debug dirs is on, directives on different lines separated by colons show the line they
293 are on rather than a general line range.
294
295 There is no ANYCASE configuration item. There was in initial beta tests, but it
296 was dropped in favor of consistent parsing syntax.
297
298 There is no V1DOLLAR configuration item. This is a TT version 1 compatibility item and
299 is not available in CET.
300
301 =back
302
303 =head1 VARIABLES
304
305 This section discusses how to use variables and expressions in the TT mini-language.
306
307 A variable is the most simple construct to insert into the TT mini language. A variable
308 name will look for the matching value inside CGI::Ex::Templates internal stash of variables
309 which is essentially a hash reference. This stash is initially populated by either passing
310 a hashref as the second argument to the process method, or by setting the "VARIABLES" or
311 "PRE_DEFINE" configuration variables.
312
313 ### some sample variables
314 my %vars = (
315 one => '1.0',
316 foo => 'bar',
317 vname => 'one',
318 some_code => sub { "You passed me (".join(', ', @_).")" },
319 some_data => {
320 a => 'A',
321 bar => 3234,
322 c => [3, 1, 4, 1, 5, 9],
323 vname => 'one',
324 },
325 my_list => [20 .. 50],
326 cet => CGI::Ex::Template->new,
327 );
328
329 ### pass the variables into the CET process
330 $cet->process($template_name, \%vars)
331 || die $cet->error;
332
333 ### pass the variables during object creation (will be available to every process call)
334 my $cet = CGI::Ex::Template->new(VARIABLES => \%vars);
335
336 =head1 GETTING VARIABLES
337
338 Once you have variables defined, they can be used directly in the template by using their name
339 in the stash. Or by using the GET directive.
340
341 [% foo %]
342 [% one %]
343 [% GET foo %]
344
345 Would print when processed:
346
347 bar
348 1.0
349 bar
350
351 To access members of a hashref or an arrayref, you can chain together the names using a ".".
352
353 [% some_data.a %]
354 [% my_list.0] [% my_list.1 %]
355 [% some_data.c.2 %]
356
357 Would print:
358
359 A
360 20 21
361 4
362
363 If the value of a variable is a code reference, it will be called. You can add a set of parenthesis
364 and arguments to pass arguments. Arguments are variables and can be as complex as necessary.
365
366 [% some_code %]
367 [% some_code() %]
368 [% some_code(foo) %]
369 [% some_code(one, 2, 3) %]
370
371 Would print:
372
373 You passed me ().
374 You passed me ().
375 You passed me (bar).
376 You passed me (1, 2, 3).
377
378 If the value of a variable is an object, methods can be called using the "." operator.
379
380 [% cet %]
381
382 [% cet.dump_parse('1 + 2').replace('\s+', ' ') %]
383
384 Would print something like:
385
386 CGI::Ex::Template=HASH(0x814dc28)
387
388 $VAR1 = [ \[ '+', '1', '2' ], 0 ];
389
390 Each type of data has virtual methods associated with them. Virtual methods
391 allow for access to common functions. For the full list of built in virtual
392 methods, please see the section titled VIRTUAL METHODS
393
394 [% foo.length %]
395 [% my_list.size %]
396 [% some_data.c.join(" | ") %]
397
398 Would print:
399
400 3
401 31
402 3 | 1 | 4 | 5 | 9
403
404 It is also possible to "interpolate" variable names using a "$". This allows for storing
405 the name of a variable inside another variable. If a variable name is a little
406 more complex, it can be embedded inside of "${" and "}".
407
408 [% $vname %]
409 [% ${vname} %]
410 [% ${some_data.vname} %]
411 [% some_data.$foo %]
412 [% some_data.${foo} %]
413
414 Would print:
415
416 1.0
417 1.0
418 1.0
419 3234
420 3234
421
422 =head2 SETTING VARIABLES.
423
424 To define variables during processing, you can use the = operator. In most cases
425 this is the same as using the SET directive.
426
427 [% a = 234 %][% a %]
428 [% SET b = "Hello" %][% b %]
429
430 Would print:
431
432 234
433 Hello
434
435 It is also possible to create arrayrefs and hashrefs.
436
437 [% a = [1, 2, 3] %]
438 [% b = {key1 => 'val1', 'key2' => 'val2'} %]
439
440 [% a.1 %]
441 [% b.key1 %] [% b.key2 %]
442
443 Would print:
444
445 2
446 val1 val2
447
448 It is possible to set multiple values at the same time.
449
450 [% SET a = 'A'
451 b = 'B'
452 c = 'C' %]
453 [% a %] [% b %] [% c %]
454
455 Would print:
456
457 A B C
458
459 It is also possible to unset variables, or to set members of
460 nested data structures.
461
462 [% a = 1 %]
463 [% SET a %]
464
465 [% b.0.c = 37 %]
466
467 ([% a %])
468 [% b.0.c %]
469
470 Would print
471
472 ()
473 37
474
475 =head1 LITERALS AND CONSTRUCTORS
476
477 The following are the types of literals allowed in CET. They can be used as arguments
478 to functions, in place of variables in directives, and in place of variables in expressions.
479
480 In CET it is also possible to call virtual methods on literal values.
481
482 =over 4
483
484 =item Integers and Numbers.
485
486 [% 23423 %] Prints an integer.
487 [% 3.14159 %] Prints a number.
488 [% pi = 3.14159 %] Sets the value of the variable.
489 [% 3.13159.length %] Prints 7 (the string length of the number)
490
491
492 =item Single quoted string.
493
494 Returns the string. No variable interpolation happens.
495
496 [% 'foobar' %] Prints "foobar".
497 [% '$foo\n' %] Prints "$foo\\n". # the \\n is a literal "\" and a "\n"
498 [% 'That\'s nice' %] Prints "That's nice".
499 [% str = 'A string' %] Sets the value of str.
500 [% 'A string'.split %] Splits the string on ' ' and returns the list.
501
502 Note: virtual methods can only be used on literal strings in CET, not in TT.
503
504 =item Double quoted string.
505
506 Returns the string. Variable interpolation happens.
507
508 [% "foobar" %] Prints "foobar".
509 [% "$foo" %] Prints "bar" (assuming the value of foo is bar).
510 [% "${foo} %] Prints "bar" (assuming the value of foo is bar).
511 [% "foobar\n" %] Prints "foobar\n". # the \n is a newline.
512 [% str = "Hello" %] Sets the value of str.
513 [% "foo".replace('foo','bar') %] Prints "bar".
514
515 Note: virtual methods can only be used on literal strings in CET, not in TT.
516
517 =item Array Constructor.
518
519 [% [1, 2, 3] %] Prints something like ARRAY(0x8309e90).
520 [% [4, 5, 6].size %] Prints 3.
521 [% [7, 8, 9].reverse.0 %] Prints 9.
522 [% array1 = [1 .. 3] %] Sets the value of array1.
523 [% array2 = [foo, 'a', []] %] Sets the value of array2.
524
525 Note: virtual methods can only be used on array contructors in CET, not in TT.
526
527 =item Hash Constructor.
528
529 [% {foo => 'bar'} %] Prints something like HASH(0x8305880)
530 [% {a => 'A', b => 'B'}.size %] Prints 2.
531 [% {'a' => 'A', 'b' => 'B'}.size %] Prints 2.
532 [% hash = {foo => 'bar', c => {}} %] Sets the value of hash.
533
534 Note: virtual methods can only be used on hash contructors in CET, not in TT.
535
536 =head1 EXPRESSIONS
537
538 Expressions are one or more variables or literals joined together
539 operators. An expression can be used anywhere a variable can be used
540 with the exception of the variable name of SET, and the filename of
541 PROCESS, INCLUDE, WRAPPER, and INSERT.
542
543 The following section shows some samples of expressions. For a full list
544 of available operators, please see the section titled OPERATORS.
545
546 [% 1 + 2 %] Prints 3
547 [% 1 + 2 * 3 %] Prints 7
548 [% (1 + 2) * 3 %] Prints 9
549
550 [% x = 2 %]
551 [% y = 3 %]
552 [% z = x * (y - 1) %] Prints 4
553
554 =head1 VIRTUAL METHODS
555
556 The following is the list of builtin virtual methods and filters that
557 can be called on each type of data.
558
559 In CGI::Ex::Template, the "|" operator can be used to call virtual
560 methods just the same way that the "." operator can. The main
561 difference between the two is that on access to hashrefs or objects,
562 the "|" means to always call the virtual method or filter rather than
563 looking in the hashref for a key by that name, or trying to call that
564 method on the object. This is similar to how TT3 will function.
565
566 =head2 SCALAR VIRTUAL METHODS AND FILTERS
567
568 The following is the list of builtin virtual methods and filters
569 that can be called on scalar data types. In CET and TT3, filters and
570 virtual methods are more closely related. In general anywhere a
571 virtual method can be used a filter can be used also - and vice versa
572 - all scalar virtual methods can be used as filters.
573
574 In addition to the filters listed below, CET will automatically load
575 Template::Filters and use them if Template::Toolkit is installed.
576
577 In addition to the scalar virtual methods, any scalar will be
578 automatically converted to a single item list if a list virtual method
579 is called on it.
580
581 =over 4
582
583 =item chunk
584
585 [% item.chunk(60).join("\n") %] Split string up into a list of chunks of text 60 chars wide.
586
587 =item collapse
588
589 [% item.collapse %] Strip leading and trailing whitespace and collapse all other space to one space.
590
591 =item defined
592
593 [% item.defined %] Always true - because the undef sub translates all undefs to ''.
594
595 =item indent
596
597 [% item.indent(3) %] Indent that number of spaces.
598
599 [% item.indent("Foo: ") %] Add the string "Foo: " to the beginning of every line.
600
601 =item eval
602
603 [% item.eval %] Process the string as though it was a template. This will start the parsing
604 engine and will use the same configuration as the current process. CET is several times
605 faster at doing this than TT is and is considered acceptable.
606
607 =item evaltt
608
609 Same as the eval filter.
610
611 =item file
612
613 Same as the redirect filter.
614
615 =item format
616
617 [% item.format('%d') %] Print the string out in the specified format. Each line is
618 processed separately.
619
620 =item hash
621
622 [% item.hash %] Returns a one item hash with a key of "value" and a value of the item.
623
624 =item html
625
626 [% item.html %] Performs a very basic html encoding (swaps out &, <, > and " for the html entities)
627
628 =item lcfirst
629
630 [% item.lcfirst %] Capitalize the leading letter.
631
632 =item length
633
634 [% item.length %] Return the length of the string.
635
636 =item lower
637
638 [% item.lower %] Return a lower-casified string.
639
640 =item match
641
642 [% item.match("(\w+) (\w+)") %] Return a list of items matching the pattern.
643
644 [% item.match("(\w+) (\w+)", 1) %] Same as before - but match globally.
645
646 =item null
647
648 [% item.null %] Do nothing.
649
650 =item remove
651
652 [% item.remove("\s+") %] Same as remove - but is global and replaces with nothing.
653
654 =item redirect
655
656 [% item.redirect("output_file.html") %] - Writes the contents out to the specified file. The filename
657 must be relative to the OUTPUT_PATH configuration variable and the OUTPUT_PATH variable must be set.
658
659 =item repeat
660
661 [% item.repeat(3) %] Repeat the item 3 times
662
663 [% item.repeat(3, ' | ') %] Repeat the item 3 times separated with ' | '
664
665 =item replace
666
667 [% item.replace("\s+", "&nbsp;") %] Globally replace all space with &nbsp;
668
669 [% item.replace("foo", "bar", 0) Replace the first instance of foo with bar.
670
671 [% item.replace("(\w+)", "($1)") %] Surround all words with parenthesis.
672
673 =item search
674
675 [% item.search("(\w+)" %] Tests if the given pattern is in the string.
676
677 =item size
678
679 [% item.size %] Always returns 1.
680
681 =item split => \&vmethod_split,
682
683 [% item.split %] Returns an arrayref from the item split on " "
684
685 [% item.split("\s+") %] Returns an arrayref from the item split on /\s+/
686
687 [% item.split("\s+", 3) %] Returns an arrayref from the item split on /\s+/ splitting until 3 elements are found.
688
689 =item stderr
690
691 [% item.stderr %] Print the item to the current STDERR handle.
692
693 =item substr
694
695 [% item.substr(i) %] Returns a substring of item starting at i and going to the end of the string.
696
697 [% item.substr(i, n) %] Returns a substring of item starting at i and going n characters.
698
699 =item trim
700
701 [% item.trim %] Strips leading and trailing whitespace.
702
703 =item ucfirst
704
705 [% item.ucfirst %] Lower-case the leading letter.
706
707 =item upper
708
709 [% item.upper %] Return a upper-casified string.
710
711 =item uri
712
713 [% item.uri %] Perform a very basic URI encoding.
714
715 =back
716
717 =head2 LIST VIRTUAL METHODS
718
719 =over 4
720
721 The following methods can be called on an arrayref type data structures (scalar
722 types will automatically promote to a single element list and call these methods
723 if needed):
724
725 =item first
726
727 [% mylist.first(3) %] Returns a list of the first 3 items in the list.
728
729 =item grep
730
731 [% mylist.grep("^\w+\.\w+$") %] Returns a list of all items matching the pattern.
732
733 =item hash
734
735 [% mylist.hash %] Returns a hashref with the array indexes as keys and the values as values.
736
737 =item join
738
739 [% mylist.join %] Joins on space.
740 [% mylist.join(", ") Joins on the passed argument.
741
742 =item last
743
744 [% mylist.last(3) %] Returns a list of the last 3 items in the list.
745
746 =item list
747
748 [% mylist.list %] Returns a reference to the list.
749
750 =item max
751
752 [% mylist.max %] Returns the last item in the array.
753
754 =item merge
755
756 [% mylist.merge(list2) %] Returns a new list with all defined items from list2 added.
757
758 =item nsort
759
760 [% mylist.nsort %] Returns the numerically sorted items of the list. If the items are
761 hashrefs, a key containing the field to sort on can be passed.
762
763 =item pop
764
765 [% mylist.pop %] Removes and returns the last element from the arrayref (the stash is modified).
766
767 =item push
768
769 [% mylist.push(23) %] Adds an element to the end of the arrayref (the stash is modified).
770
771 =item reverse
772
773 [% mylist.reverse %] Returns the list in reverse order.
774
775 =item shift
776
777 [% mylist.shift %] Removes and returns the first element of the arrayref (the stash is modified).
778
779 =item size
780
781 [% mylist.size %] Returns the number of elements in the array.
782
783 =item slice
784
785 [% mylist.slice(i, n) %] Returns a list from the arrayref beginning at index i and continuing for n items.
786
787 =item sort
788
789 [% mylist.sort %] Returns the alphabetically sorted items of the list. If the items are
790 hashrefs, a key containing the field to sort on can be passed.
791
792 =item splice
793
794 [% mylist.splice(i, n) %] Removes items from array beginning at i and continuing for n items.
795
796 [% mylist.splice(i, n, list2) %] Same as before, but replaces removed items with the items
797 from list2.
798
799 =item unique
800
801 [% mylist.unique %] Return a list of the unique items in the array.
802
803 =item unshift
804
805 [% mylist.unshift(23) %] Adds an item to the beginning of the arrayref.
806
807 =back 4
808
809 =head2 HASH VIRTUAL METHODS
810
811 The following methods can be called on hash type data structures:
812
813 =over 4
814
815 =item defined
816
817 [% myhash.defined('a') %] Checks if a is defined in the hash.
818
819 =item delete
820
821 [% myhash.delete('a') %] Deletes the item from the hash.
822
823 =item each
824
825 [% myhash.each.join(", ") %] Turns the contents of the hash into a list - subject
826 to change as TT is changing the operations of each and list.
827
828 =item exists
829
830 [% myhash.exists('a') %] Checks if a is in the hash.
831
832 =item hash
833
834 [% myhash.hash %] Returns a reference to the hash.
835
836 =item import
837
838 [% myhash.import(hash2) %] Overlays the keys of hash2 over the keys of myhash.
839
840 =item keys
841
842 [% myhash.keys.join(', ') %] Returns an arrayref of the keys of the hash.
843
844 =item list
845
846 [% myhash.list %] Returns an arrayref with the hash as a single value (subject to change).
847
848 =item pairs
849
850 [% myhash.pairs %] Returns an arrayref of hashrefs where each hash contains {key => $key, value => $value}
851 for each value of the hash.
852
853 =item nsort
854
855 [% myhash.nsort.join(", ") %] Returns a numerically sorted list of the keys.
856
857 =item size
858
859 [% myhash.size %] Returns the number of key/value pairs in the hash.
860
861 =item sort
862
863 [% myhash.sort.join(", ") Returns an alphabetically sorted list.
864
865 =item values
866
867 [% myhash.values.join(', ') %] Returns an arrayref of the values of the hash.
868
869 =back
870
871 =head1 DIRECTIVES
872
873 This section contains the alphabetical list of DIRECTIVES available
874 in the TT language. DIRECTIVES are the "functions" and control
875 structures that implement the Template Toolkit mini-language. For
876 further discussion and examples, please refer to the TT directives
877 documentation.
878
879
880 =over 4
881
882 =item C<BLOCK>
883
884 Saves a block of text under a name for later use in PROCESS, INCLUDE,
885 and WRAPPER directives. Blocks may be placed anywhere within the
886 template being processed including after where they are used.
887
888 [% BLOCK foo %]Some text[% END %]
889 [% PROCESS foo %]
890
891 Would print
892
893 Some text
894
895 [% INCLUDE foo %]
896 [% BLOCK foo %]Some text[% END %]
897
898 Would print
899
900 Some text
901
902 Anonymous BLOCKS can be used for capturing.
903
904 [% a = BLOCK %]Some text[% END %][% a %]
905
906 Would print
907
908 Some text
909
910 Anonymous BLOCKS can be used with macros.
911
912
913 =item C<BREAK>
914
915 Alias for LAST. Used for exiting FOREACH and WHILE loops.
916
917 =item C<CALL>
918
919 Calls the variable (and any underlying coderefs) as in the GET method, but
920 always returns an empty string.
921
922 =item C<CASE>
923
924 Used with the SWITCH directive. See the L</"SWITCH"> directive.
925
926 =item C<CATCH>
927
928 Used with the TRY directive. See the L</"TRY"> directive.
929
930 =item C<CLEAR>
931
932 Clears any of the content currently generated in the innermost block
933 or template. This can be useful when used in conjunction with the TRY
934 statement to clear generated content if an error occurs later.
935
936 =item C<DEBUG>
937
938 Used to reset the DEBUG_FORMAT configuration variable, or to turn
939 DEBUG statements on or off. This only has effect if the DEBUG_DIRS or
940 DEBUG_ALL flags were passed to the DEBUG configuration variable.
941
942 [% DEBUG format '($file) (line $line) ($text)' %]
943 [% DEBUG on %]
944 [% DEBUG off %]
945
946 =item C<DEFAULT>
947
948 Similar to SET, but only sets the value if a previous value was not
949 defined or was zero length.
950
951 [% DEFAULT foo = 'bar' %][% foo %] => 'bar'
952
953 [% foo = 'baz' %][% DEFAULT foo = 'bar' %][% foo %] => 'baz'
954
955 =item C<DUMP>
956
957 This is not provided in TT. DUMP inserts a Data::Dumper printout
958 of the variable or expression. If no argument is passed it will
959 dump the entire contents of the current variable stash (with
960 private keys removed.
961
962 If the template is being processed in a web request, DUMP will html
963 encode the DUMP automatically.
964
965 [% DUMP %] # dumps everything
966
967 [% DUMP 1 + 2 %]
968
969 =item C<ELSE>
970
971 Used with the IF directive. See the L</"IF"> directive.
972
973 =item C<ELSIF>
974
975 Used with the IF directive. See the L</"IF"> directive.
976
977 =item C<END>
978
979 Used to end a block directive.
980
981 =item C<FILTER>
982
983 Used to apply different treatments to blocks of text. It may operate as a BLOCK
984 directive or as a post operative directive. CET supports all of the filters in
985 Template::Filters. The lines between scalar virtual methods and filters is blurred (or
986 non-existent) in CET. Anything that is a scalar virtual method may be used as a FILTER.
987
988 TODO - enumerate the at least 7 ways to pass and use filters.
989
990 =item C<'|'>
991
992 Alias for the FILTER directive. Note that | is similar to the
993 '.' in CGI::Ex::Template. Therefore a pipe cannot be used directly after a
994 variable name in some situations (the pipe will act only on that variable).
995 This is the behavior employed by TT3.
996
997 =item C<FINAL>
998
999 Used with the TRY directive. See the L</"TRY"> directive.
1000
1001 =item C<FOR>
1002
1003 Alias for FOREACH
1004
1005 =item C<FOREACH>
1006
1007 Allows for iterating over the contents of any arrayref. If the variable is not an
1008 arrayref, it is automatically promoted to one.
1009
1010 [% FOREACH i IN [1 .. 3] %]
1011 The variable i = [% i %]
1012 [%~ END %]
1013
1014 [% a = [1 .. 3] %]
1015 [% FOREACH j IN a %]
1016 The variable j = [% j %]
1017 [%~ END %]
1018
1019 Would print:
1020
1021 The variable i = 1
1022 The variable i = 2
1023 The variable i = 3
1024
1025 The variable j = 1
1026 The variable j = 2
1027 The variable j = 3
1028
1029 You can also use the "=" instead of "IN" or "in".
1030
1031 [% FOREACH i = [1 .. 3] %]
1032 The variable i = [% i %]
1033 [%~ END %]
1034
1035 Same as before.
1036
1037 Setting into a variable is optional.
1038
1039 [% a = [1 .. 3] %]
1040 [% FOREACH a %] Hi [% END %]
1041
1042 Would print:
1043
1044 hi hi hi
1045
1046 If the item being iterated is a hashref and the FOREACH does not
1047 set into a variable, then values of the hashref are copied into
1048 the variable stash.
1049
1050 [% FOREACH [{a => 1}, {a => 2}] %]
1051 Key a = [% a %]
1052 [%~ END %]
1053
1054 Would print:
1055
1056 Key a = 1
1057 Key a = 2
1058
1059 The FOREACH process uses the CGI::Ex::Template::Iterator class to handle
1060 iterations (It is compatible with Template::Iterator). During the FOREACH
1061 loop an object blessed into the iterator class is stored in the variable "loop".
1062
1063 The loop variable provides the following information during a FOREACH:
1064
1065 index - the current index
1066 max - the max index of the list
1067 size - the number of items in the list
1068 count - index + 1
1069 number - index + 1
1070 first - true if on the first item
1071 last - true if on the last item
1072 next - return the next item in the list
1073 prev - return the previous item in the list
1074
1075 The following:
1076
1077 [% FOREACH [1 .. 3] %] [% loop.count %]/[% loop.size %] [% END %]
1078
1079 Would print:
1080
1081 1/3 2/3 3/3
1082
1083 The iterator is also available using a plugin. This allows for access
1084 to multiple "loop" variables in a nested FOREACH directive.
1085
1086 [%~ USE outer_loop = Iterator(["a", "b"]) %]
1087 [%~ FOREACH i = outer_loop %]
1088 [%~ FOREACH j = ["X", "Y"] %]
1089 [% outer_loop.count %]-[% loop.count %] = ([% i %] and [% j %])
1090 [%~ END %]
1091 [%~ END %]
1092
1093 Would print:
1094
1095 1-1 = (a and X)
1096 1-2 = (a and Y)
1097 2-1 = (b and X)
1098 2-2 = (b and Y)
1099
1100 FOREACH may also be used as a post operative directive.
1101
1102 [% "$i" FOREACH i = [1 .. 5] %] => 12345
1103
1104 =item C<GET>
1105
1106 Return the value of a variable or expression.
1107
1108 [% GET a %]
1109
1110 The GET keyword may be omitted.
1111
1112 [% a %]
1113
1114 [% 7 + 2 - 3 %] => 6
1115
1116 See the section on VARIABLES.
1117
1118 =item C<IF (IF / ELSIF / ELSE)>
1119
1120 Allows for conditional testing. Expects an expression as its only
1121 argument. If the expression is true, the contents of its block are
1122 processed. If false, the processor looks for an ELSIF block. If an
1123 ELSIF's expression is true then it is processed. Finally it looks for
1124 an ELSE block which is processed if none of the IF or ELSIF's
1125 expressions were true.
1126
1127 [% IF a == b %]A equaled B[% END %]
1128
1129 [% IF a == b -%]
1130 A equaled B
1131 [%- ELSIF a == c -%]
1132 A equaled C
1133 [%- ELSE -%]
1134 Couldn't determine that A equaled anything.
1135 [%- END %]
1136
1137 IF may also be used as a post operative directive.
1138
1139 [% 'A equaled B' IF a == b %]
1140
1141 =item C<INCLUDE>
1142
1143 Parse the contents of a file or block and insert them. Variables defined
1144 or modifications made to existing variables are discarded after
1145 a template is included.
1146
1147 [% INCLUDE path/to/template.html %]
1148
1149 [% INCLUDE "path/to/template.html" %]
1150
1151 [% file = "path/to/template.html" %]
1152 [% INCLUDE $file %]
1153
1154 [% BLOCK foo %]This is foo[% END %]
1155 [% INCLUDE foo %]
1156
1157 Arguments may also be passed to the template:
1158
1159 [% INCLUDE "path/to/template.html" a = "An arg" b = "Another arg" %]
1160
1161 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1162 or RELATIVE configuration items are set.
1163
1164 =item C<INSERT>
1165
1166 Insert the contents of a file without template parsing.
1167
1168 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1169 or RELATIVE configuration items are set.
1170
1171 =item C<LAST>
1172
1173 Used to exit out of a WHILE or FOREACH loop.
1174
1175 =item C<MACRO>
1176
1177 Takes a directive and turns it into a variable that can take arguments.
1178
1179 [% MACRO foo(i, j) BLOCK %]You passed me [% i %] and [% j %].[% END %]
1180
1181 [%~ foo("a", "b") %]
1182 [% foo(1, 2) %]
1183
1184 Would print:
1185
1186 You passed me a and b.
1187 You passed me 1 and 2.
1188
1189 Another example:
1190
1191 [% MACRO bar(max) FOREACH i = [1 .. max] %]([% i %])[% END %]
1192
1193 [%~ bar(4) %]
1194
1195 Would print:
1196
1197 (1)(2)(3)(4)
1198
1199 =item C<META>
1200
1201 Used to define variables that will be available via either the
1202 template or component namespace.
1203
1204 Once defined, they cannot be overwritten.
1205
1206 [% template.foobar %]
1207 [%~ META foobar = 'baz' %]
1208 [%~ META foobar = 'bing' %]
1209
1210 Would print:
1211
1212 baz
1213
1214 =item C<NEXT>
1215
1216 Used to go to the next iteration of a WHILE or FOREACH loop.
1217
1218 =item C<PERL>
1219
1220 Only available if the EVAL_PERL configuration item is true (default is false).
1221
1222 Allow eval'ing the block of text as perl. The block will be parsed and then eval'ed.
1223
1224 [% a = "BimBam" %]
1225 [%~ PERL %]
1226 my $a = "[% a %]";
1227 print "The variable \$a was \"$a\"";
1228 $stash->set('b', "FooBar");
1229 [% END %]
1230 [% b %]
1231
1232 Would print:
1233
1234 The variable $a was "BimBam"
1235 FooBar
1236
1237 During execution, anything printed to STDOUT will be inserted into the template. Also,
1238 the $stash and $context variables are set and are references to objects that mimic the
1239 interface provided by Template::Context and Template::Stash. These are provided for
1240 compatibility only. $self contains the current CGI::Ex::Template object.
1241
1242 =item C<PROCESS>
1243
1244 Parse the contents of a file or block and insert them. Unlike INCLUDE,
1245 no variable localization happens so variables defined or modifications made
1246 to existing variables remain after the template is processed.
1247
1248 [% PROCESS path/to/template.html %]
1249
1250 [% PROCESS "path/to/template.html" %]
1251
1252 [% file = "path/to/template.html" %]
1253 [% PROCESS $file %]
1254
1255 [% BLOCK foo %]This is foo[% END %]
1256 [% PROCESS foo %]
1257
1258 Arguments may also be passed to the template:
1259
1260 [% PROCESS "path/to/template.html" a = "An arg" b = "Another arg" %]
1261
1262 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1263 or RELATIVE configuration items are set.
1264
1265 =item C<RAWPERL>
1266
1267 Only available if the EVAL_PERL configuration item is true (default is false).
1268 Similar to the PERL directive, but you will need to append
1269 to the $output variable rather than just calling PRINT.
1270
1271 =item C<RETURN>
1272
1273 Used to exit the innermost block or template and continue processing
1274 in the surrounding block or template.
1275
1276 =item C<SET>
1277
1278 Used to set variables.
1279
1280 [% SET a = 1 %][% a %] => "1"
1281 [% a = 1 %][% a %] => "1"
1282 [% b = 1 %][% SET a = b %][% a %] => "1"
1283 [% a = 1 %][% SET a %][% a %] => ""
1284 [% SET a = [1, 2, 3] %][% a.1 %] => "2"
1285 [% SET a = {b => 'c'} %][% a.b %] => "c"
1286
1287 =item C<STOP>
1288
1289 Used to exit the entire process method (out of all blocks and templates).
1290 No content will be processed beyond this point.
1291
1292 =item C<SWITCH>
1293
1294 Allow for SWITCH and CASE functionality.
1295
1296 [% a = "hi" %]
1297 [% b = "bar" %]
1298 [% SWITCH a %]
1299 [% CASE "foo" %]a was foo
1300 [% CASE b %]a was bar
1301 [% CASE ["hi", "hello"] %]You said hi or hello
1302 [% CASE DEFAULT %]I don't know what you said
1303 [% END %]
1304
1305 Would print:
1306
1307 You said hi or hello
1308
1309 =item C<TAGS>
1310
1311 Change the type of enclosing braces used to delineate template tags. This
1312 remains in effect until the end of the enclosing block or template or until
1313 the next TAGS directive. Either a named set of tags must be supplied, or
1314 two tags themselves must be supplied.
1315
1316 [% TAGS html %]
1317
1318 [% TAGS <!-- --> %]
1319
1320 The named tags are (duplicated from TT):
1321
1322 template => ['[%', '%]'], # default
1323 metatext => ['%%', '%%'], # Text::MetaText
1324 star => ['[*', '*]'], # TT alternate
1325 php => ['<?', '?>'], # PHP
1326 asp => ['<%', '%>'], # ASP
1327 mason => ['<%', '>' ], # HTML::Mason
1328 html => ['<!--', '-->'], # HTML comments
1329
1330 =item C<THROW>
1331
1332 Allows for throwing an exception. If the exception is not caught
1333 via the TRY DIRECTIVE, the template will abort processing of the directive.
1334
1335 [% THROW mytypes.sometime 'Something happened' arg1 => val1 %]
1336
1337 See the TRY directive for examples of usage.
1338
1339 =item C<TRY>
1340
1341 The TRY block directive will catch exceptions that are thrown
1342 while processing its block (It cannot catch parse errors unless
1343 they are in included files or evaltt'ed strings. The TRY block
1344 will then look for a CATCH block that will be processed. While
1345 it is being processed, the "error" variable will be set with the thrown
1346 exception as the value. After the TRY block - the FINAL
1347 block will be ran whether or not an error was thrown (unless a CATCH
1348 block throws an error).
1349
1350 Note: Parse errors cannot be caught unless they are in an eval FILTER, or are
1351 in a separate template being INCLUDEd or PROCESSed.
1352
1353 [% TRY %]
1354 Nothing bad happened.
1355 [% CATCH %]
1356 Caught the error.
1357 [% FINAL %]
1358 This section runs no matter what happens.
1359 [% END %]
1360
1361 Would print:
1362
1363 Nothing bad happened.
1364 This section runs no matter what happens.
1365
1366 Another example:
1367
1368 [% TRY %]
1369 [% THROW "Something happened" %]
1370 [% CATCH %]
1371 Error: [% error %]
1372 Error.type: [% error.type %]
1373 Error.info: [% error.info %]
1374 [% FINAL %]
1375 This section runs no matter what happens.
1376 [% END %]
1377
1378 Would print:
1379
1380 Error: undef error - Something happened
1381 Error.type: undef
1382 Error.info: Something happened
1383 This section runs no matter what happens.
1384
1385 You can give the error a type and more information including named arguments.
1386 This information replaces the "info" property of the exception.
1387
1388 [% TRY %]
1389 [% THROW foo.bar "Something happened" "grrrr" foo => 'bar' %]
1390 [% CATCH %]
1391 Error: [% error %]
1392 Error.type: [% error.type %]
1393 Error.info: [% error.info %]
1394 Error.info.0: [% error.info.0 %]
1395 Error.info.1: [% error.info.1 %]
1396 Error.info.args.0: [% error.info.args.0 %]
1397 Error.info.foo: [% error.info.foo %]
1398 [% END %]
1399
1400 Would print something like:
1401
1402 Error: foo.bar error - HASH(0x82a395c)
1403 Error.type: foo.bar
1404 Error.info: HASH(0x82a395c)
1405 Error.info.0: Something happened
1406 Error.info.1: grrrr
1407 Error.info.args.0: Something happened
1408 Error.info.foo: bar
1409
1410 You can also give the CATCH block a type to catch. And you
1411 can nest TRY blocks. If types are specified, CET will try and
1412 find the closest matching type. Also, an error object can
1413 be re-thrown using $error as the argument to THROW.
1414
1415 [% TRY %]
1416 [% TRY %]
1417 [% THROW foo.bar "Something happened" %]
1418 [% CATCH bar %]
1419 Caught bar.
1420 [% CATCH DEFAULT %]
1421 Caught default - but rethrew.
1422 [% THROW $error %]
1423 [% END %]
1424 [% CATCH foo %]
1425 Caught foo.
1426 [% CATCH foo.bar %]
1427 Caught foo.bar.
1428 [% CATCH %]
1429 Caught anything else.
1430 [% END %]
1431
1432 Would print:
1433
1434 Caught default - but rethrew.
1435
1436 Caught foo.bar.
1437
1438 =item C<UNLESS>
1439
1440 Same as IF but condition is negated.
1441
1442 [% UNLESS 0 %]hi[% END %] => hi
1443
1444 Can also be a post operative directive.
1445
1446 =item C<USE>
1447
1448 Allows for loading a Template::Toolkit style plugin.
1449
1450 [% USE iter = Iterator(['foo', 'bar']) %]
1451 [%~ iter.get_first %]
1452 [% iter.size %]
1453
1454 Would print:
1455
1456 foo
1457 2
1458
1459 Note that it is possible to send arguments to the new object
1460 constructor. It is also possible to omit the variable name being
1461 assigned. In that case the name of the plugin becomes the variable.
1462
1463 [% USE Iterator(['foo', 'bar', 'baz']) %]
1464 [%~ Iterator.get_first %]
1465 [% Iterator.size %]
1466
1467 Would print:
1468
1469 foo
1470 3
1471
1472 Plugins that are loaded are looked up for in the namespace listed in
1473 the PLUGIN_BASE directive which defaults to Template::Plugin. So in
1474 the previous example, if Template::Toolkit was installed, the iter
1475 object would loaded by the class Template::Plugin::Iterator. In CET,
1476 an effective way to disable plugins is to set the PLUGIN_BASE to a
1477 non-existent base such as "_" (In TT it will still fall back to look
1478 in Template::Plugin).
1479
1480 Note: The iterator plugin will fall back and use
1481 CGI::Ex::Template::Iterator if Template::Toolkit is not installed. No
1482 other plugins come installed with CGI::Ex::Template.
1483
1484 The names of the Plugin being loaded from PLUGIN_BASE are case
1485 insensitive. However, using case insensitive names is bad as it
1486 requires scanning the @INC directories for any module matching the
1487 PLUGIN_BASE and caching the result (OK - not that bad).
1488
1489 If the plugin is not found and the LOAD_PERL directive is set, then
1490 CET will try and load a module by that name (note: this type of lookup
1491 is case sensitive and will not scan the @INC dirs for a matching
1492 file).
1493
1494 # The LOAD_PERL directive should be set to 1
1495 [% USE cet = CGI::Ex::Template %]
1496 [%~ cet.dump_parse('2 * 3').replace('\s+', ' ') %]
1497
1498 Would print:
1499
1500 $VAR1 = [ \[ '*', '2', '3' ], 0 ];
1501
1502 See the PLUGIN_BASE, and PLUGINS configuration items.
1503
1504 See the documentation for Template::Manual::Plugins.
1505
1506 =item C<WHILE>
1507
1508 Will process a block of code while a condition is true.
1509
1510 [% WHILE i < 3 %]
1511 [%~ i = i + 1 %]
1512 i = [% i %]
1513 [%~ END %]
1514
1515 Would print:
1516
1517 i = 1
1518 i = 2
1519 i = 3
1520
1521 You could also do:
1522
1523 [% i = 4 %]
1524 [% WHILE (i = i - 1) %]
1525 i = [% i %]
1526 [%~ END %]
1527
1528 Would print:
1529
1530 i = 3
1531 i = 2
1532 i = 1
1533
1534 Note that (f = f - 1) is a valid expression that returns the value
1535 of the assignment. The parenthesis are not optional.
1536
1537 WHILE has a built in limit of 1000 iterations. This is controlled by the
1538 global variable $WHILE_MAX in CGI::Ex::Template.
1539
1540 WHILE may also be used as a post operative directive.
1541
1542 [% "$i" WHILE (i = i + 1) < 7 %] => 123456
1543
1544 =item C<WRAPPER>
1545
1546 Block directive. Processes contents of its block and then passes them
1547 in the [% content %] variable to the block or filename listed in the
1548 WRAPPER tag.
1549
1550 [% WRAPPER foo %]
1551 My content to be processed.[% a = 2 %]
1552 [% END %]
1553
1554 [% BLOCK foo %]
1555 A header ([% a %]).
1556 [% content %]
1557 A footer ([% a %]).
1558 [% END %]
1559
1560 This would print.
1561
1562 A header (2).
1563 My content to be processed.
1564 A footer (2).
1565
1566 The WRAPPER directive may also be used as a post directive.
1567
1568 [% BLOCK baz %]([% content %])[% END -%]
1569 [% "foobar" WRAPPER baz %]
1570
1571 Would print
1572
1573 (foobar)');
1574
1575 =back
1576
1577
1578
1579 =head1 OPERATORS
1580
1581 The following operators are available in CGI::Ex::Template. Except
1582 where noted these are the same operators available in TT. They are
1583 listed in the order of their precedence (the higher the precedence the
1584 tighter it binds).
1585
1586 =over 4
1587
1588 =item C<.>
1589
1590 Binary. The dot operator. Allows for accessing sub-members, methods, or
1591 virtual methods of nested data structures.
1592
1593 my $obj->process(\$content, {a => {b => [0, {c => [34, 57]}]}}, \$output);
1594
1595 [% a.b.1.c.0 %] => 34
1596
1597 Note: on access to hashrefs, any hash keys that match the sub key name
1598 will be used before a virtual method of the same name. For example if
1599 a passed hash contained pair with a keyname "defined" and a value of
1600 "2", then any calls to hash.defined(another_keyname) would always
1601 return 2 rather than using the vmethod named "defined." To get around
1602 this limitation use the "|" operator (listed next). Also - on objects
1603 the "." will always try and call the method by that name. To always
1604 call the vmethod - use "|".
1605
1606 =item C<|>
1607
1608 Binary. The pipe operator. Similar to the dot operator. Allows for
1609 explicit calling of virtual methods and filters (filters are "merged"
1610 with virtual methods in CGI::Ex::Template and TT3) when accessing
1611 hashrefs and objects. See the note for the "." operator.
1612
1613 The pipe character is similar to TT2 in that it can be used in place
1614 of a directive as an alias for FILTER. It similar to TT3 in that it
1615 can be used for virtual method access. This duality is one source of
1616 difference between CGI::Ex::Template and TT2 compatibility. Templates
1617 that have directives that end with a variable name that then use the
1618 "|" directive to apply a filter will be broken as the "|" will be
1619 applied to the variable name.
1620
1621 The following two cases will do the same thing.
1622
1623 [% foo | html %]
1624
1625 [% foo FILTER html %]
1626
1627 Though they do the same thing, internally, foo|html is stored as a
1628 single variable while "foo FILTER html" is stored as the variable foo
1629 which is then passed to the FILTER html.
1630
1631 A TT2 sample that would break in CGI::Ex::Template or TT3 is:
1632
1633 [% PROCESS foo a = b | html %]
1634
1635 Under TT2 the content returned by "PROCESS foo a = b" would all be
1636 passed to the html filter. Under CGI::Ex::Template and TT3, b would
1637 be passed to the html filter before assigning it to the variable "a"
1638 before the template foo was processed.
1639
1640 A simple fix is to do any of the following:
1641
1642 [% PROCESS foo a = b FILTER html %]
1643
1644 [% | html %][% PROCESS foo a = b %][% END %]
1645
1646 [% FILTER html %][% PROCESS foo a = b %][% END %]
1647
1648 This shouldn't be too much hardship and offers the great return of disambiguating
1649 virtual method access.
1650
1651 =item C<** ^ pow>
1652
1653 Binary. X raised to the Y power. This isn't available in TT 2.15.
1654
1655 [% 2 ** 3 %] => 8
1656
1657 =item C<!>
1658
1659 Unary not. Negation of the value.
1660
1661 =item C<- unary_minus>
1662
1663 Unary minus. Returns the value multiplied by -1. The operator
1664 "unary_minus" is used internally by CGI::Ex::Template to provide for -
1665 to be listed in the precedence table twice.
1666
1667 [% a = 1 ; b = -a ; b %] => -1
1668
1669 =item C<*>
1670
1671 Binary. Multiplication.
1672
1673 =item C</ div DIV>
1674
1675 Binary. Division. Note that / is floating point division, but div and
1676 DIV are integer division.
1677
1678 [% 10 / 4 %] => 2.5
1679 [% 10 div 4 %] => 2
1680
1681 =item C<% mod MOD>
1682
1683 Binary. Modulus.
1684
1685 [% 15 % 8 %] => 7
1686
1687 =item C<+>
1688
1689 Binary. Addition.
1690
1691 =item C<->
1692
1693 Binary. Minus.
1694
1695 =item C<_ ~>
1696
1697 Binary. String concatenation.
1698
1699 [% "a" ~ "b" %] => ab
1700
1701 =item C<< < > <= >= >>
1702
1703 Binary. Numerical comparators.
1704
1705 =item C<lt gt le ge>
1706
1707 Binary. String comparators.
1708
1709 =item C<== eq>
1710
1711 Binary. Equality test. TT chose to use Perl's eq for both operators.
1712 There is no test for numeric equality.
1713
1714 =item C<!= ne>
1715
1716 Binary. Non-equality test. TT chose to use Perl's ne for both
1717 operators. There is no test for numeric non-equality.
1718
1719 =item C<&&>
1720
1721 Multiple arity. And. All values must be true. If all values are true, the last
1722 value is returned as the truth value.
1723
1724 [% 2 && 3 && 4 %] => 4
1725
1726 =item C<||>
1727
1728 Multiple arity. Or. The first true value is returned.
1729
1730 [% 0 || '' || 7 %] => 7
1731
1732 =item C<..>
1733
1734 Binary. Range creator. Returns an arrayref containing the values
1735 between and including the first and last arguments.
1736
1737 [% t = [1 .. 5] %] => variable t contains an array with 1,2,3,4, and 5
1738
1739 It is possible to place multiple ranges in the same [] constructor. This is not available in TT.
1740
1741 [% t = [1..3, 6..8] %] => variable t contains an array with 1,2,3,6,7,8
1742
1743 The .. operator is the only operator that returns a list of items.
1744
1745 =item C<? :>
1746
1747 Trinary. Can be nested with other ?: pairs.
1748
1749 [% 1 ? 2 : 3 %] => 2
1750 [% 0 ? 2 : 3 %] => 3
1751
1752 =item C<=>
1753
1754 Assignment. Sets the left-hand side to the value of the righthand side. In order
1755 to not conflict with SET, FOREACH and other operations, this operator is only
1756 available in parenthesis. Returns the value of the righthand side.
1757
1758 [% (a = 1) %] --- [% a %] => 1 --- 1
1759
1760 =item C<not NOT>
1761
1762 Lower precedence version of the '!' operator.
1763
1764 =item C<and AND>
1765
1766 Lower precedence version of the '&&' operator.
1767
1768 =item C<or OR>
1769
1770 Lower precedence version of the '||' operator.
1771
1772 =item C<hash>
1773
1774 Multiple arity. This operator is not used in TT. It is used internally
1775 by CGI::Ex::Template to delay the creation of a hash until the
1776 execution of the compiled template.
1777
1778 =item C<array>
1779
1780 Multiple arity. This operator is not used in TT. It is used internally
1781 by CGI::Ex::Template to delay the creation of an array until the
1782 execution of the compiled template.
1783
1784 =back
1785
1786
1787 =head1 CHOMPING
1788
1789 Chomping refers to the handling of whitespace immediately before and
1790 immediately after template tags. By default, nothing happens to this
1791 whitespace. Modifiers can be placed just inside the opening and just
1792 before the closing tags to control this behavior.
1793
1794 Additionally, the PRE_CHOMP and POST_CHOMP configuration variables can
1795 be set and will globally control all chomping behavior for tags that
1796 do not have their own chomp modifier. PRE_CHOMP and POST_CHOMP can
1797 be set to any of the following values:
1798
1799 none: 0 + Template::Constants::CHOMP_NONE
1800 one: 1 - Template::Constants::CHOMP_ONE
1801 collapse: 2 = Template::Constants::CHOMP_COLLAPSE
1802 greedy: 3 ~ Template::Constants::CHOMP_GREEDY
1803
1804 =over 4
1805
1806 =item CHOMP_NONE
1807
1808 Don't do any chomping. The "+" sign is used to indicate CHOMP_NONE.
1809
1810 Hello.
1811
1812 [%+ "Hi." +%]
1813
1814 Howdy.
1815
1816 Would print:
1817
1818 Hello.
1819
1820 Hi.
1821
1822 Howdy.
1823
1824 =item CHOMP_ONE (formerly known as CHOMP_ALL)
1825
1826 Delete any whitespace up to the adjacent newline. The "-" is used to indicate CHOMP_ONE.
1827
1828 Hello.
1829
1830 [%- "Hi." -%]
1831
1832 Howdy.
1833
1834 Would print:
1835
1836 Hello.
1837 Hi.
1838 Howdy.
1839
1840 =item CHOMP_COLLAPSE
1841
1842 Collapse adjacent whitespace to a single space. The "=" is used to indicate CHOMP_COLLAPSE.
1843
1844 Hello.
1845
1846 [%- "Hi." -%]
1847
1848 Howdy.
1849
1850 Would print:
1851
1852 Hello. Hi. Howdy.
1853
1854 =item CHOMP_GREEDY
1855
1856 Remove all adjacent whitespace. The "~" is used to indicate CHOMP_GREEDY.
1857
1858 Hello.
1859
1860 [%- "Hi." -%]
1861
1862 Howdy.
1863
1864 Would print:
1865
1866 Hello.Hi.Howdy.
1867
1868 =head1 CONFIGURATION
1869
1870 The following TT2 configuration variables are supported (in
1871 alphabetical order). Note: for further discussion you can refer to
1872 the TT config documentation.
1873
1874 These variables should be passed to the "new" constructor.
1875
1876 my $obj = CGI::Ex::Template->new(
1877 VARIABLES => \%hash_of_variables,
1878 AUTO_RESET => 0,
1879 TRIM => 1,
1880 POST_CHOMP => "=",
1881 PRE_CHOMP => "-",
1882 );
1883
1884
1885 =over 4
1886
1887 =item ABSOLUTE
1888
1889 Boolean. Default false. Are absolute paths allowed for included files.
1890
1891 =item AUTO_RESET
1892
1893 Boolean. Default 1. Clear blocks that were set during the process method.
1894
1895 =item BLOCKS
1896
1897 A hashref of blocks that can be used by the process method.
1898
1899 BLOCKS => {
1900 block_1 => sub { ... }, # coderef that returns a block
1901 block_2 => 'A String', # simple string
1902 },
1903
1904 Note that a Template::Document cannot be supplied as a value (TT
1905 supports this). However, it is possible to supply a value that is
1906 equal to the hashref returned by the load_parsed_tree method.
1907
1908 =item CACHE_SIZE
1909
1910 Number of compiled templates to keep in memory. Default undef.
1911 Undefined means to allow all templates to cache. A value of 0 will
1912 force no caching. The cache mechanism will clear templates that have
1913 not been used recently.
1914
1915 =item COMPILE_DIR
1916
1917 Base directory to store compiled templates. Default undef. Compiled
1918 templates will only be stored if one of COMPILE_DIR and COMPILE_EXT is
1919 set.
1920
1921 =item COMPILE_EXT
1922
1923 Extension to add to stored compiled template filenames. Default undef.
1924
1925 =item CONSTANTS
1926
1927 Hashref. Used to define variables that will be "folded" into the
1928 compiled template. Variables defined here cannot be overridden.
1929
1930 CONSTANTS => {my_constant => 42},
1931
1932 A template containing:
1933
1934 [% constants.my_constant %]
1935
1936 Will have the value 42 compiled in.
1937
1938 Constants defined in this way can be chained as in [%
1939 constant.foo.bar.baz %] but may only interpolate values that are set
1940 before the compile process begins. This goes one step beyond TT in
1941 that any variable set in VARIABLES, or PRE_DEFINE, or passed to the
1942 process method are allowed - they are not in TT. Variables defined in
1943 the template are not available during the compile process.
1944
1945 GOOD:
1946
1947 CONSTANTS => {
1948 foo => {
1949 bar => {baz => 42},
1950 bim => 57,
1951 },
1952 bing => 'baz',
1953 bang => 'bim',
1954 },
1955 VARIABLES => {
1956 bam => 'bar',
1957 },
1958
1959 In the template
1960
1961 [% constants.foo.${constants.bang} %]
1962
1963 Will correctly print 57.
1964
1965 GOOD (non-tt behavior)
1966
1967 [% constants.foo.$bam.${constants.bing} %]
1968
1969 CGI::Ex::Template will print 42 because the value of bam is
1970 known at compile time. TT would print '' because the value of $bam
1971 is not yet defined in the TT engine.
1972
1973 BAD:
1974
1975 In the template:
1976
1977 [% bam = 'somethingelse' %]
1978 [% constants.foo.$bam.${constants.bing} %]
1979
1980 Will still print 42 because the value of bam used comes from
1981 variables defined before the template was compiled. TT will still print ''.
1982
1983 =item CONSTANT_NAMESPACE
1984
1985 Allow for setting the top level of values passed in CONSTANTS. Default
1986 value is 'constants'.
1987
1988 =item DEBUG
1989
1990 Takes a list of constants |'ed together which enables different
1991 debugging modes. Alternately the lowercase names may be used (multiple
1992 values joined by a ",".
1993
1994 The only supported TT values are:
1995 DEBUG_UNDEF (2) - debug when an undefined value is used.
1996 DEBUG_DIRS (8) - debug when a directive is used.
1997 DEBUG_ALL (2047) - turn on all debugging.
1998
1999 Either of the following would turn on undef and directive debugging:
2000
2001 DEBUG => 'undef, dirs', # preferred
2002 DEBUG => 2 | 8,
2003 DEBUG => DEBUG_UNDEF | DEBUG_DIRS, # constants from Template::Constants
2004
2005 =item DEBUG_FORMAT
2006
2007 Change the format of messages inserted when DEBUG has DEBUG_DIRS set on.
2008 This essentially the same thing as setting the format using the DEBUG
2009 directive.
2010
2011 =item DEFAULT
2012
2013 The name of a default template file to use if the passed on is not found.
2014
2015 =item DELIMITER
2016
2017 String to use to split INCLUDE_PATH with. Default is :. It is more
2018 straight forward to just send INCLUDE_PATH an arrayref of paths.
2019
2020 =item END_TAG
2021
2022 Set a string to use as the closing delimiter for TT. Default is "%]".
2023
2024 =item EVAL_PERL
2025
2026 Boolean. Default false. If set to a true value, PERL and RAWPERL blocks
2027 will be allowed to run. This is a potential security hole, as arbitrary
2028 perl can be included in the template. If Template::Toolkit is installed,
2029 a true EVAL_PERL value also allows the perl and evalperl filters to be used.
2030
2031 =item FILTERS
2032
2033 Allow for passing in TT style filters.
2034
2035 my $filters = {
2036 filter1 => sub { my $str = shift; $s =~ s/./1/gs; $s },
2037 filter2 => [sub { my $str = shift; $s =~ s/./2/gs; $s }, 0],
2038 filter3 => [sub { my ($context, @args) = @_; return sub { my $s = shift; $s =~ s/./3/gs; $s } }, 1],
2039 };
2040
2041 my $str = q{
2042 [% a = "Hello" %]
2043 1([% a | filter1 %])
2044 2([% a | filter2 %])
2045 3([% a | filter3 %])
2046 };
2047
2048 my $obj = CGI::Ex::Template->new(FILTERS => $filters);
2049 $obj->process(\$str) || die $obj->error;
2050
2051 Would print:
2052
2053 (11111)
2054 (22222)
2055 (33333)
2056
2057 Filters passed in as an arrayref should contain a coderef and a value
2058 indicating if they are dynamic or static (true meaning dynamic). The
2059 dynamic filters are passed the pseudo context object and any arguments
2060 and should return a coderef that will be called as the filter. The filter
2061 coderef is then passed the string.
2062
2063 =item INCLUDE_PATH
2064
2065 A string or an arrayref or coderef that returns an arrayref that
2066 contains directories to look for files included by processed
2067 templates.
2068
2069 =item INCLUDE_PATHS
2070
2071 Non-TT item. Same as INCLUDE_PATH but only takes an arrayref. If not specified
2072 then INCLUDE_PATH is turned into an arrayref and stored in INCLUDE_PATHS.
2073 Overrides INCLUDE_PATH.
2074
2075 =item INTERPOLATE
2076
2077 Boolean. Specifies whether variables in text portions of the template will be
2078 interpolated. For example, the $variable and ${var.value} would be substituted
2079 with the appropriate values from the variable cache (if INTERPOLATE is on).
2080
2081 [% IF 1 %]The variable $variable had a value ${var.value}[% END %]
2082
2083
2084 =item LOAD_PERL
2085
2086 Indicates if the USE directive can fall back and try and load a perl module
2087 if the indicated module was not found in the PLUGIN_BASE path. See the
2088 USE directive.
2089
2090 =item NAMESPACE
2091
2092 No Template::Namespace::Constants support. Hashref of hashrefs representing
2093 constants that will be folded into the template at compile time.
2094
2095 CGI::Ex::Template->new(NAMESPACE => {constants => {
2096 foo => 'bar',
2097 }});
2098
2099 Is the same as
2100
2101 CGI::Ex::Template->new(CONSTANTS => {
2102 foo => 'bar',
2103 });
2104
2105 Any number of hashes can be added to the NAMESPACE hash.
2106
2107 =item OUTPUT
2108
2109 Alternate way of passing in the output location for processed templates.
2110 If process is not passed an output argument, it will look for this value.
2111
2112 See the process method for a listing of possible values.
2113
2114 =item OUTPUT_PATH
2115
2116 Base path for files written out via the process method or via the redirect
2117 and file filters. See the redirect virtual method and the process method
2118 for more information.
2119
2120 =item PLUGINS
2121
2122 A hashref of mappings of plugin modules.
2123
2124 PLUGINS => {
2125 Iterator => 'Template::Plugin::Iterator',
2126 DBI => 'MyDBI',
2127 },
2128
2129 See the USE directive for more information.
2130
2131 =item PLUGIN_BASE
2132
2133 Default value is Template::Plugin. The base module namespace
2134 that template plugins will be looked for. See the USE directive
2135 for more information.
2136
2137 =item POST_CHOMP
2138
2139 Set the type of chomping at the ending of a tag.
2140 See the section on chomping for more information.
2141
2142 =item POST_PROCESS
2143
2144 A list of templates to be processed and appended to the content
2145 after the main template. During this processing the "template"
2146 namespace will contain the name of the main file being processed.
2147
2148 This is useful for adding a global footer to all templates.
2149
2150 =item PRE_CHOMP
2151
2152 Set the type of chomping at the beginning of a tag.
2153 See the section on chomping for more information.
2154
2155 =item PRE_DEFINE
2156
2157 Same as the VARIABLES configuration item.
2158
2159 =item PRE_PROCESS
2160
2161 A list of templates to be processed before and pre-pended to the content
2162 before the main template. During this processing the "template"
2163 namespace will contain the name of the main file being processed.
2164
2165 This is useful for adding a global header to all templates.
2166
2167 =item PROCESS
2168
2169 Specify a file to use as the template rather than the one passed in
2170 to the ->process method.
2171
2172 =item RECURSION
2173
2174 Boolean. Default false. Indicates that INCLUDED or PROCESSED files
2175 can refer to each other in a circular manner. Be careful about recursion.
2176
2177 =item RELATIVE
2178
2179 Boolean. Default false. If true, allows filenames to be specified
2180 that are relative to the currently running process.
2181
2182 =item START_TAG
2183
2184 Set a string to use as the opening delimiter for TT. Default is "[%".
2185
2186 =item TAG_STYLE
2187
2188 Allow for setting the type of tag delimiters to use for parsing the TT.
2189 See the TAGS directive for a listing of the available types.
2190
2191 =item TRIM
2192
2193 Remove leading and trailing whitespace from blocks and templates.
2194 This operation is performed after all enclosed template tags have
2195 been executed.
2196
2197 =item UNDEFINED_ANY
2198
2199 This is not a TT configuration option. This option expects to be a code
2200 ref that will be called if a variable is undefined during a call to get_variable.
2201 It is passed the variable identity array as a single argument. This
2202 is most similar to the "undefined" method of Template::Stash. It allows
2203 for the "auto-defining" of a variable for use in the template. It is
2204 suggested that UNDEFINED_GET be used instead as UNDEFINED_ANY is a little
2205 to general in defining variables.
2206
2207 You can also sub class the module and override the undefined_any method.
2208
2209 =item UNDEFINED_GET
2210
2211 This is not a TT configuration option. This option expects to be a code
2212 ref that will be called if a variable is undefined during a call to GET.
2213 It is passed the variable identity array as a single argument. This is more useful
2214 than UNDEFINED_ANY in that it is only called during a GET directive
2215 rather than in embedded expressions (such as [% a || b || c %]).
2216
2217 You can also sub class the module and override the undefined_get method.
2218
2219 =item VARIABLES
2220
2221 A hashref of variables to initialize the template stash with. These
2222 variables are available for use in any of the executed templates.
2223 See the section on VARIABLES for the types of information that can be passed in.
2224
2225 =back
2226
2227
2228
2229 =head1 UNSUPPORTED TT CONFIGURATION
2230
2231 =over 4
2232
2233 =item ANYCASE
2234
2235 This will not be supported. You will have to use the full case directive names.
2236 (It was in the beta code but was removed prior to release).
2237
2238 =item WRAPPER
2239
2240 This will be supported - just not done yet.
2241
2242 =item ERROR
2243
2244 This will be supported - just not done yet.
2245
2246 =item V1DOLLAR
2247
2248 This will not be supported.
2249
2250 =item LOAD_TEMPLATES
2251
2252 CGI::Ex::Template has its own mechanism for loading and storing
2253 compiled templates. TT would use a Template::Provider that would
2254 return a Template::Document. The closest thing in CGI::Ex::Template
2255 is the load_parsed_template method. There is no immediate plan to
2256 support the TT behavior.
2257
2258 =item LOAD_PLUGINS
2259
2260 CGI::Ex::Template uses its own mechanism for loading plugins. TT
2261 would use a Template::Plugins object to load plugins requested via the
2262 USE directive. The functionality for doing this in CGI::Ex::Template
2263 is contained in the list_plugins method and the play_USE method. There
2264 is no immediate plan to support the TT behavior.
2265
2266 Full support is offered for the PLUGINS and LOAD_PERL configuration items.
2267
2268 Also note that CGI::Ex::Template only natively supports the Iterator plugin.
2269 Any of the other plugins requested will need to provided by installing
2270 Template::Toolkit or the appropriate plugin module.
2271
2272 =item LOAD_FILTERS
2273
2274 CGI::Ex::Template uses its own mechanism for loading filters. TT
2275 would use the Template::Filters object to load filters requested via the
2276 FILTER directive. The functionality for doing this in CGI::Ex::Template
2277 is contained in the list_filters method and the get_variable method.
2278
2279 Full support is offered for the FILTERS configuration item.
2280
2281 =item TOLERANT
2282
2283 This option is used by the LOAD_TEMPLATES and LOAD_PLUGINS options and
2284 is not applicable in CGI::Ex::Template.
2285
2286 =item SERVICE
2287
2288 CGI::Ex::Template has no concept of service (theoretically the CGI::Ex::Template
2289 is the "service").
2290
2291 =item CONTEXT
2292
2293 CGI::Ex::Template provides its own pseudo context object to plugins,
2294 filters, and perl blocks. The CGI::Ex::Template model doesn't really
2295 allow for a separate context. CGI::Ex::Template IS the context.
2296
2297 =item STASH
2298
2299 CGI::Ex::Template manages its own stash of variables. A pseudo stash
2300 object is available via the pseudo context object for use in plugins,
2301 filters, and perl blocks.
2302
2303 =item PARSER
2304
2305 CGI::Ex::Template has its own built in parser. The closest similarity is
2306 the parse_tree method. The output of parse_tree is an optree that is
2307 later run by execute_tree.
2308
2309 =item GRAMMAR
2310
2311 CGI::Ex::Template maintains its own grammar. The grammar is defined
2312 in the parse_tree method and the callbacks listed in the global
2313 $DIRECTIVES hashref.
2314
2315 =back
2316
2317
2318 =head1 VARIABLE PARSE TREE
2319
2320 CGI::Ex::Template parses templates into an tree of operations. Even
2321 variable access is parsed into a tree. This is done in a manner
2322 somewhat similar to the way that TT operates except that nested
2323 variables such as foo.bar|baz contain the '.' or '|' in between each
2324 name level. Operators are parsed and stored as part of the variable (it
2325 may be more appropriate to say we are parsing a term or an expression).
2326
2327 The following table shows a variable or expression and the corresponding parsed tree
2328 (this is what the parse_variable method would return).
2329
2330 one [ 'one', 0 ]
2331 one() [ 'one', [] ]
2332 one.two [ 'one', 0, '.', 'two', 0 ]
2333 one|two [ 'one', 0, '|', 'two', 0 ]
2334 one.$two [ 'one', 0, '.', ['two', 0 ], 0 ]
2335 one(two) [ 'one', [ ['two', 0] ] ]
2336 one.${two().three} [ 'one', 0, '.', ['two', [], '.', 'three', 0], 0]
2337 2.34 2.34
2338 "one" "one"
2339 "one"|length [ \"one", 0, '|', 'length', 0 ]
2340 "one $a two" [ \ [ '~', 'one ', ['a', 0], ' two' ], 0 ]
2341 [0, 1, 2] [ \ [ 'array', 0, 1, 2 ], 0 ]
2342 [0, 1, 2].size [ \ [ 'array', 0, 1, 2 ], 0, '.', 'size', 0 ]
2343 ['a', a, $a ] [ \ [ 'array', 'a', ['a', 0], [['a', 0], 0] ], 0]
2344 {a => 'b'} [ \ [ 'hash', 'a', 'b' ], 0 ]
2345 {a => 'b'}.size [ \ [ 'hash', 'a', 'b' ], 0, '.', 'size', 0 ]
2346 {$a => b} [ \ [ 'hash', ['a', 0], ['b', 0] ], 0 ]
2347 1 + 2 [ \ [ '+', 1, 2 ], 0]
2348 a + b [ \ [ '+', ['a', 0], ['b', 0] ], 0 ]
2349 a * (b + c) [ \ [ '*', ['a', 0], [ \ ['+', ['b', 0], ['c', 0]], 0 ]], 0 ]
2350 (a + b) [ \ [ '+', ['a', 0], ['b', 0] ]], 0 ]
2351 (a + b) * c [ \ [ '*', [ \ [ '+', ['a', 0], ['b', 0] ], 0 ], ['c', 0] ], 0 ]
2352 a ? b : c [ \ [ '?', ['a', 0], ['b', 0], ['c', 0] ], 0 ]
2353 a || b || c [ \ [ '||', ['a', 0], [ \ [ '||', ['b', 0], ['c', 0] ], 0 ] ], 0 ]
2354 ! a [ \ [ '!', ['a', 0] ], 0 ]
2355
2356 Some notes on the parsing.
2357
2358 Operators are parsed as part of the variable and become part of the variable tree.
2359
2360 Operators are stored in the variable tree using a reference to the arrayref - which
2361 allows for quickly descending the parsed variable tree and determining that the next
2362 node is an operator.
2363
2364 Parenthesis () can be used at any point in an expression to disambiguate precedence.
2365
2366 "Variables" that appear to be literal strings or literal numbers
2367 are returned as the literal (no operator tree).
2368
2369 The following perl can be typed at the command line to view the parsed variable tree:
2370
2371 perl -e 'use CGI::Ex::Template; print CGI::Ex::Template::dump_parse("foo.bar + 2")."\n"'
2372
2373 Also the following can be included in a template to view the output in a template:
2374
2375 [% USE cet = CGI::Ex::Template %]
2376 [%~ cet.dump_parse('foo.bar + 2').replace('\s+', ' ') %]
2377
2378
2379 =head1 SEMI PUBLIC METHODS
2380
2381 The following list of methods are other interesting methods of CET that
2382 may be re-implemented by subclasses of CET.
2383
2384 =over 4
2385
2386 =item C<dump_parse>
2387
2388 This method allows for returning a Data::Dumper dump of a parsed variable. It is mainly used for testing.
2389
2390 =item C<exception>
2391
2392 Creates an exception object blessed into the package listed in
2393 $CGI::Ex::Template::PACKAGE_EXCEPTION.
2394
2395 =item C<execute_tree>
2396
2397 Executes a parsed tree (returned from parse_tree)
2398
2399 =item C<get_variable>
2400
2401 Turns a variable identity array into the parsed variable. This
2402 method is also responsible for playing operators and running virtual methods
2403 and filters. The method could more accurately be called play_expression.
2404
2405 =item C<include_filename>
2406
2407 Takes a file path, and resolves it into the full filename using
2408 paths from INCLUDE_PATH or INCLUDE_PATHS.
2409
2410 =item C<_insert>
2411
2412 Resolves the file passed, and then returns its contents.
2413
2414 =item C<list_filters>
2415
2416 Dynamically loads the filters list from Template::Filters when a filter
2417 is used that is not natively implemented in CET.
2418
2419 =item C<list_plugins>
2420
2421 Returns an arrayref of modules that are under a base Namespace.
2422
2423 my @modules = @{ $self->list_plugins({base => 'Template::Plugins'}) }:
2424
2425 =item C<load_parsed_tree>
2426
2427 Given a filename or a string reference will return a parsed document
2428 hash that contains the parsed tree.
2429
2430 my $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");
2431
2432 =item C<parse_args>
2433
2434 Allow for the multitudinous ways that TT parses arguments. This allows
2435 for positional as well as named arguments. Named arguments can be separated with a "=" or "=>",
2436 and positional arguments should be separated by " " or ",". This only returns an array
2437 of parsed variables. Use vivify_args to translate to the actual values.
2438
2439 =item C<parse_tree>
2440
2441 Used by load_parsed_tree. This is the main grammar engine of the program. It
2442 uses method in the $DIRECTIVES hashref to parse different DIRECTIVE TYPES.
2443
2444 =item C<parse_variable>
2445
2446 Used to parse a variable, an expression, a literal string, or a number. It
2447 returns a parsed variable tree. Samples of parsed variables can be found in the VARIABLE PARSE TREE
2448 section.
2449
2450 =item C<set_variable>
2451
2452 Used to set a variable. Expects a variable identity array and the value to set. It
2453 will autovifiy as necessary.
2454
2455 =item C<throw>
2456
2457 Creates an exception object from the arguments and dies.
2458
2459 =item C<undefined_any>
2460
2461 Called during get_variable if a value is returned that is undefined. This could
2462 be used to magically create variables on the fly. This is similar to Template::Stash::undefined.
2463 It is suggested that undefined_get be used instead. Default behavior returns undef. You
2464 may also pass a coderef via the UNDEFINED_ANY configuration variable. Also, you can try using
2465 the DEBUG => 'undef', configuration option which will throw an error on undefined variables.
2466
2467 =item C<undefined_get>
2468
2469 Called when a variable is undefined during a GET directive. This is useful to
2470 see if a value that is about to get inserted into the text is undefined. undefined_any is a little
2471 too general for most cases. Also, you may pass a coderef via the UNDEFINED_GET configuration variable.
2472
2473 =item C<vivify_args>
2474
2475 Turns an arrayref of arg identities parsed by parse_args and turns
2476 them into the actual values.
2477
2478 =back
2479
2480
2481 =head1 OTHER UTILITY METHODS
2482
2483 The following is a brief list of other methods used by CET. Generally, these
2484 shouldn't be overwritten by subclasses.
2485
2486 =over 4
2487
2488 =item C<apply_precedence>
2489
2490 Allows for parsed operator array to be translated to a tree based
2491 upon operator precedence.
2492
2493 =item C<context>
2494
2495 Used to create a "pseudo" context object that allows for portability
2496 of TT plugins, filters, and perl blocks that need a context object.
2497
2498 =ITEM C<DEBUG>
2499
2500 TT2 Holdover that is used once for binmode setting during a TT2 test.
2501
2502 =item C<debug_node>
2503
2504 Used to get debug info on a directive if DEBUG_DIRS is set.
2505
2506 =item C<filter_*>
2507
2508 Methods by these names implement filters that are more than one line.
2509
2510 =item C<get_line_number_by_index>
2511
2512 Used to turn string index position into line number
2513
2514 =item C<interpolate_node>
2515
2516 Used for parsing text nodes for dollar variables when interpolate is on.
2517
2518 =item C<parse_*>
2519
2520 Methods by these names are used by parse_tree to parse the template. These are the grammar.
2521
2522 =item C<play_*>
2523
2524 Methods by these names are used by execute_tree to execute the parsed tree.
2525
2526 =item C<play_operator>
2527
2528 Used to execute any found operators
2529
2530 =item C<_process>
2531
2532 Called by process and the PROCESS, INCLUDE and other directives.
2533
2534 =item C<slurp>
2535
2536 Reads contents of passed filename - throws file exception on error.
2537
2538 =item C<split_paths>
2539
2540 Used to split INCLUDE_PATH or other directives if an arrayref is not passed.
2541
2542 =item C<_vars>
2543
2544 Return a reference to the current stash of variables. This is currently only used
2545 by the pseudo context object and may disappear at some point.
2546
2547 =item C<vmethod_*>
2548
2549 Methods by these names implement virtual methods that are more than one line.
2550
2551 =item C<weak_copy>
2552
2553 Used to create a weak reference to self to avoid circular references. (this
2554 is needed by macros)
2555
2556 =back
2557
2558
2559 =head1 AUTHOR
2560
2561 Paul Seamons <paul at seamons dot com>
2562
2563 =cut
This page took 0.13083 seconds and 3 git commands to generate.