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