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