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