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