]> Dogcows Code - chaz/p5-CGI-Ex/blob - lib/CGI/Ex/Template.pod
CGI::Ex 2.13
[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 ### Template::Toolkit style usage
8
9 my $t = CGI::Ex::Template->new(
10 INCLUDE_PATH => ['/path/to/templates'],
11 );
12
13 my $swap = {
14 key1 => 'val1',
15 key2 => 'val2',
16 code => sub { 42 },
17 hash => {a => 'b'},
18 };
19
20 # print to STDOUT
21 $t->process('my/template.tt', $swap)
22 || die $t->error;
23
24 # process into a variable
25 my $out = '';
26 $t->process('my/template.tt', $swap, \$out);
27
28 ### CET uses the same syntax and configuration as Template::Toolkit
29
30
31 ### HTML::Template style usage
32
33 my $t = CGI::Ex::Template->new(
34 filename => 'my/template.ht',
35 path => ['/path/to/templates'],
36 );
37
38 my $swap = {
39 key1 => 'val1',
40 key2 => 'val2',
41 code => sub { 42 },
42 hash => {a => 'b'},
43 };
44
45 $t->param($swap);
46
47 # print to STDOUT (errors die)
48 $t->output(print_to => \*STDOUT);
49
50 # process into a variable
51 my $out = $t->output;
52
53 ### CET can also use the same syntax and configuration as HTML::Template
54
55 =head1 DESCRIPTION
56
57 CGI::Ex::Template happened by accident (accidentally on purpose). The
58 CGI::Ex::Template (CET hereafter) was originally a part of the CGI::Ex
59 suite that performed simple variable interpolation. It used TT2 style
60 variables in TT2 style tags "[% foo.bar %]". That was all the
61 original CGI::Ex::Template did. This was fine and dandy for a couple
62 of years. In winter of 2005-2006 CET was revamped to add a few
63 features. One thing led to another and soon CET provided for most of
64 the features of TT2 as well as some from TT3. CGI::Ex::Template is a
65 full-featured implementation of the Template::Toolkit language.
66
67 As of version 2.13, CGI::Ex::Template also provides near full
68 compatibility with HTML::Template (HT), HTML::Template::JIT (HTJ), and
69 HTML::Template::Expr (HTE). Version 2.13 introduced the SYNTAX
70 configuration allowing for inclusion of TT style templates in HT and
71 vice versa. It also provided the HTML::Template output and param
72 methods which allow CET to provide the HTML::Template interface. It
73 was possible to add this extra functionality because CGI::Ex::Template
74 employs an open architecture.
75
76 CGI::Ex::Template uses a recursive regex based grammar (early versions
77 before the 2.10 release did not). This allows for the embedding of
78 opening and closing tags inside other tags (as in [% a = "[% 1 + 2 %]"
79 ; a|eval %]). The individual methods such as parse_expr and play_expr
80 may be used by external applications to add TT style variable parsing
81 to other applications.
82
83 CGI::Ex::Template is fast but CGI::Ex::Template::XS is even faster.
84 If CGI::Ex::Template isn't fast enough for you, the XS version has key
85 methods coded in C and provides a noticable improvement over the
86 non-XS version. CET by itself is generally faster than TT, HT, and HTE.
87 The XS version is nearly always faster - even than HTJ. CET also uses less
88 memory than TT and HTE, and only a little more than HT. (This is all
89 as of version 2.13 in May 2007 - those other modules will undoubtedly
90 receive updates that will improve their performance).
91
92 Most of the standard Template::Toolkit documentation covering
93 directives, variables, configuration, plugins, filters, syntax, and
94 vmethods should apply to CET just fine (This pod tries to explain
95 everything - but there is too much). The section on differences
96 between CET and TT will explain what too look out for.
97
98 Additionally, most of the standard HTML::Template and
99 HTML::Template::Expr documentation covering methods, variables,
100 expressions, and syntax will apply to CET just fine as well.
101
102 So should you use CGI::Ex::Template ? Well, try it out. It may
103 give you no visible improvement. Or it could.
104
105 =head1 PUBLIC METHODS
106
107 The following section lists most of the publicly available methods. Some less
108 commonly used public methods are listed later in this document.
109
110 =over 4
111
112 =item C<new>
113
114 my $obj = CGI::Ex::Template->new({
115 INCLUDE_PATH => ['/my/path/to/content', '/my/path/to/content2'],
116 });
117
118 Arguments may be passed as a hash or as a hashref. Returns a CGI::Ex::Template object.
119
120 There are currently no errors during CGI::Ex::Template object creation. If you are
121 using the HTML::Template interface, this is different behavior. The document is
122 not parsed until the output or process methods are called.
123
124 =item C<process>
125
126 This is the main method call for starting processing. Any errors that result in the
127 template processing being stopped will be stored and available via the ->error method.
128 This is the TT compatible method - see the output method for HT compatibility.
129
130 my $t = CGI::Ex::Template->new;
131 $t->process($in, $swap, $out)
132 || die $t->error;
133
134 Process takes three arguments.
135
136 The $in argument can be any one of:
137
138 String containing the filename of the template to be processed. The filename should
139 be relative to INCLUDE_PATH. (See INCLUDE_PATH, ABSOLUTE, and RELATIVE configuration items).
140 In memory caching and file side caching are available for this type.
141
142 A reference to a scalar containing the contents of the template to be processed.
143
144 A coderef that will be called to return the contents of the template.
145
146 An open filehandle that will return the contents of the template when read.
147
148 The $swap argument should be hashref containing key value pairs that will be
149 available to variables swapped into the template. Values can be hashrefs, hashrefs
150 of hashrefs and so on, arrayrefs, arrayrefs of arrayrefs and so on, coderefs, objects,
151 and simple scalar values such as numbers and strings. See the section on variables.
152
153 The $out argument can be any one of:
154
155 undef - meaning to print the completed template to STDOUT.
156
157 String containing a filename. The completed template will be placed in the file.
158
159 A reference to a string. The contents will be appended to the scalar reference.
160
161 A coderef. The coderef will be called with the contents as a single argument.
162
163 An object that can run the method "print". The contents will be passed as
164 a single argument to print.
165
166 An arrayref. The contents will be pushed onto the array.
167
168 An open filehandle. The contents will be printed to the open handle.
169
170 Additionally - the $out argument can be configured using the OUTPUT configuration
171 item.
172
173 The process method defaults to using the "cet" syntax which will parse TT3 and most
174 TT2 documents. To parse HT or HTE documents, you must pass the SYNTAX configuration
175 item to the "new" method. All calls to process would then default to HTE syntax.
176
177 my $obj = CGI::Ex::Template->new(SYNTAX => 'hte');
178
179 =item C<process_simple>
180
181 Similar to the process method but with the following restrictions:
182
183 The $in parameter is limited to a filename or a reference a string containing the contents.
184
185 The $out parameter may only be a reference to a scalar string that output will be appended to.
186
187 Additionally, the following configuration variables will be ignored: VARIABLES,
188 PRE_DEFINE, BLOCKS, PRE_PROCESS, PROCESS, POST_PROCESS, AUTO_RESET, OUTPUT.
189
190 =item C<error>
191
192 Should something go wrong during a "process" command, the error that occurred can
193 be retrieved via the error method.
194
195 $obj->process('somefile.html', {a => 'b'}, \$string_ref)
196 || die $obj->error;
197
198 =item C<output>
199
200 HTML::Template way to process a template. The output method requires that a filename,
201 filehandle, scalarref, or arrayref argument was passed to the new method. All of
202 the HT calling conventions for new are supported. The key difference is that CET will
203 not actually process the template until the output method is called.
204
205 my $obj = CGI::Ex::Template->new(filename => 'myfile.html');
206 $obj->param(\%swap);
207 print $obj->output;
208
209 See the HTML::Template documentation for more information.
210
211 The output method defaults to using the "hte" syntax which will parse HTE and HT documents.
212 To parse TT3 or TT2 documents, you must pass the SYNTAX configuration
213 item to the "new" method. All calls to process would then default to TT3 syntax.
214
215 my $obj = CGI::Ex::Template->new(SYNTAX => 'tt3');
216
217 Any errors that occur during the output method will die with the error as the die value.
218
219 =item C<param>
220
221 HTML::Template way to get or set variable values that will be used by the output method.
222
223 my $val = $obj->param('key'); # get one value
224
225 $obj->param(key => $val); # set one value
226
227 $obj->param(key => $val, key2 => $val2); # set multiple
228
229 $obj->param({key => $val, key2 => $val2}); # set multiple
230
231 See the HTML::Template documentation for more information.
232
233 Note: CET does not support the die_on_bad_params configuration. This is because CET
234 does not resolve variable names until the output method is called.
235
236 =item C<define_vmethod>
237
238 This method is available for defining extra Virtual methods or filters. This method is similar
239 to Template::Stash::define_vmethod.
240
241 CGI::Ex::Template->define_vmethod(
242 'text',
243 reverse => sub { my $item = shift; return scalar reverse $item },
244 );
245
246 =item C<register_function>
247
248 This is the HTML::Template way of defining text vmethods. It is the same as
249 calling define_vmethod with "text" as the first argument.
250
251 CGI::Ex::Template->register_function(
252 reverse => sub { my $item = shift; return scalar reverse $item },
253 );
254
255 =item C<define_directive>
256
257 This method can be used for adding new directives or overridding existing
258 ones.
259
260 CGI::Ex::Template->define_directive(
261 MYDIR => {
262 parse_sub => sub {}, # parse additional items in the tag
263 play_sub => sub {
264 my ($self, $ref, $node, $out_ref) = @_;
265 $$out_ref .= "I always say the same thing!";
266 return;
267 },
268 is_block => 1, # is this block like
269 is_postop => 0, # not a post operative directive
270 no_interp => 1, # no interpolation in this block
271 continues => undef, # it doesn't "continue" any other directives
272 },
273 );
274
275 Now with a template like:
276
277 my $str = "([% MYDIR %]This is something[% END %])";
278 CGI::Ex::Template->new->process(\$str);
279
280 You will get:
281
282 (I always say the same thing!)
283
284 We'll add more details in later revisions of this document.
285
286 =item C<define_syntax>
287
288 This method can be used for adding other syntaxes to or overridding
289 existing ones in the list of choices available in CET. The syntax can
290 be chosen by the SYNTAX configuration item.
291
292 CGI::Ex::Template->define_syntax(
293 my_uber_syntax => sub {
294 my $self = shift;
295 local $self->{'V2PIPE'} = 0;
296 local $self->{'V2EQUALS'} = 0;
297 local $self->{'PRE_CHOMP'} = 0;
298 local $self->{'POST_CHOMP'} = 0;
299 local $self->{'NO_INCLUDES'} = 0;
300 return $self->parse_tree_tt3(@_);
301 },
302 );
303
304 The subroutine that is used must return an opcode tree (AST) that
305 can be played by the execute_tree method.
306
307 =item C<define_operator>
308
309 This method allows for adding new operators or overriding existing ones.
310
311 CGI::Ex::Template->define_operator({
312 type => 'right', # can be one of prefix, postfix, right, left, none, ternary, assign
313 precedence => 84, # relative precedence for resolving multiple operators without parens
314 symbols => ['foo', 'FOO'], # any mix of chars can be used for the operators
315 play_sub => sub {
316 my ($one, $two) = @_;
317 return "You've been foo'ed ($one, $two)";
318 },
319 });
320
321 You can then use it in a template as in the following:
322
323 my $str = "[% 'ralph' foo 1 + 2 * 3 %]";
324 CGI::Ex::Template->new->process(\$str);
325
326 You will get:
327
328 You've been foo'ed (ralph, 7)
329
330 Future revisions of this document will include more samples.
331
332 =back
333
334 =head1 TODO
335
336 Move module to its own namespace.
337
338 Cleanup operator API to allow for easier full customization of
339 operators.
340
341 Give better examples of overriding directives, syntax, and operators.
342
343 Add more functions to the XS version.
344
345 Find other syntaxes to include.
346
347 =head1 HOW IS CGI::Ex::Template DIFFERENT from Template::Toolkit
348
349 CET uses the same base template syntax and configuration items as TT2,
350 but the internals of CET were written from scratch. Additionally much
351 of the planned TT3 syntax is supported as well as most of that of
352 HTML::Template::Expr. The following is a list of some of the ways
353 that the configuration and syntax of CET are different from that of
354 TT2. Note: items that are planned to work in TT3 are marked with
355 (TT3).
356
357 =over 4
358
359 =item
360
361 Numerical hash keys work
362
363 [% a = {1 => 2} %]
364
365 =item
366
367 Quoted hash key interpolation is fine
368
369 [% a = {"$foo" => 1} %]
370
371 =item
372
373 Multiple ranges in same constructor
374
375 [% a = [1..10, 21..30] %]
376
377 =item
378
379 Constructor types can call virtual methods. (TT3)
380
381 [% a = [1..10].reverse %]
382
383 [% "$foo".length %]
384
385 [% 123.length %] # = 3
386
387 [% 123.4.length %] # = 5
388
389 [% -123.4.length %] # = -5 ("." binds more tightly than "-")
390
391 [% (a ~ b).length %]
392
393 [% "hi".repeat(3) %] # = hihihi
394
395 [% {a => b}.size %] # = 1
396
397 =item
398
399 The "${" and "}" variable interpolators can contain expressions,
400 not just variables.
401
402 [% [0..10].${ 1 + 2 } %] # = 4
403
404 [% {ab => 'AB'}.${ 'a' ~ 'b' } %] # = AB
405
406 [% color = qw/Red Blue/; FOR [1..4] ; color.${ loop.index % color.size } ; END %]
407 # = RedBlueRedBlue
408
409 =item
410
411 You can use regular expression quoting.
412
413 [% "foo".match( /(F\w+)/i ).0 %] # = foo
414
415 =item
416
417 Tags can be nested.
418
419 [% f = "[% (1 + 2) %]" %][% f|eval %] # = 3
420
421 =item
422
423 Arrays can be accessed with non-integer numbers.
424
425 [% [0..10].${ 2.3 } %] # = 3
426
427 =item
428
429 Reserved names are less reserved. (TT3)
430
431 [% GET GET %] # gets the variable named "GET"
432
433 [% GET $GET %] # gets the variable who's name is stored in "GET"
434
435 =item
436
437 Filters and SCALAR_OPS are interchangeable. (TT3)
438
439 [% a | length %]
440
441 [% b . lower %]
442
443 =item
444
445 Pipe "|" can be used anywhere dot "." can be and means to call
446 the virtual method. (TT3)
447
448 [% a = {size => "foo"} %][% a.size %] # = foo
449
450 [% a = {size => "foo"} %][% a|size %] # = 1 (size of hash)
451
452 =item
453
454 Pipe "|" and "." can be mixed. (TT3)
455
456 [% "aa" | repeat(2) . length %] # = 4
457
458 =item
459
460 Added V2PIPE configuration item
461
462 Restores the behavior of the pipe operator to be
463 compatible with TT2.
464
465 With V2PIPE = 1
466
467 [% PROCESS a | repeat(2) %] # = value of block or file a repeated twice
468
469 With V2PIPE = 0 (default)
470
471 [% PROCESS a | repeat(2) %] # = process block or file named a ~ a
472
473 =item
474
475 Added V2EQUALS configuration item
476
477 Allows for turning off TT2 "==" behavior. Defaults to 1
478 in TT syntaxes and to 0 in HT syntaxes.
479
480 [% CONFIG V2EQUALS => 1 %][% ('7' == '7.0') || 0 %]
481 [% CONFIG V2EQUALS => 0 %][% ('7' == '7.0') || 0 %]
482
483 Prints
484
485 0
486 1
487
488 =item
489
490 Added Virtual Object Namespaces. (TT3)
491
492 The Text, List, and Hash types give direct access
493 to virtual methods.
494
495 [% a = "foobar" %][% Text.length(a) %] # = 6
496
497 [% a = [1 .. 10] %][% List.size(a) %] # = 10
498
499 [% a = {a=>"A", b=>"B"} ; Hash.size(a) %] = 2
500
501 [% foo = {a => 1, b => 2}
502 | Hash.keys
503 | List.join(", ") %] # = a, b
504
505 =item
506
507 Added "fmt" scalar, list, and hash virtual methods.
508
509 [% list.fmt("%s", ", ") %]
510
511 [% hash.fmt("%s => %s", "\n") %]
512
513 =item
514
515 Added missing HTML::Template::Expr vmethods
516
517 The following vmethods were added - they correspond to the
518 perl functions of the same name.
519
520 abs
521 atan2
522 cos
523 exp
524 hex
525 lc
526 log
527 oct
528 sin
529 sprintf
530 sqrt
531 srand
532 uc
533
534 =item
535
536 Allow all Scalar vmethods to behave as top level functions.
537
538 [% sprintf("%d %d", 7, 8) %] # = "7 8"
539
540 The following are equivalent in CET:
541
542 [% "abc".length %]
543 [% length("abc") %]
544
545 This feature may be disabling by setting the
546 VMETHOD_FUNCTIONS configuration item to 0.
547
548 This is similar to how HTML::Template::Expr operates, but
549 now you can use this functionality in TT templates as well.
550
551 =item
552
553 Whitespace is less meaningful. (TT3)
554
555 [% 2-1 %] # = 1 (fails in TT2)
556
557 =item
558
559 Added pow operator.
560
561 [% 2 ** 3 %] [% 2 pow 3 %] # = 8 8
562
563 =item
564
565 Added string comparison operators (gt ge lt le cmp)
566
567 [% IF "a" lt "b" %]a is less[% END %]
568
569 =item
570
571 Added numeric comparison operator (<=>)
572
573 This can be used to make up for the fact that TT2 made == the
574 same as eq (which will hopefully change - use eq when you mean eq).
575
576 [% IF ! (a <=> b) %]a == b[% END %]
577
578 [% IF (a <=> b) %]a != b[% END %]
579
580 =item
581
582 Added self modifiers (+=, -=, *=, /=, %=, **=, ~=). (TT3)
583
584 [% a = 2; a *= 3 ; a %] # = 6
585 [% a = 2; (a *= 3) ; a %] # = 66
586
587 =item
588
589 Added pre and post increment and decrement (++ --). (TT3)
590
591 [% ++a ; ++a %] # = 12
592 [% a-- ; a-- %] # = 0-1
593
594 =item
595
596 Added qw// contructor. (TT3)
597
598 [% a = qw(a b c); a.1 %] # = b
599
600 [% qw/a b c/.2 %] # = c
601
602 =item
603
604 Added regex contructor. (TT3)
605
606 [% "FOO".match(/(foo)/i).0 %] # = FOO
607
608 [% a = /(foo)/i; "FOO".match(a).0 %] # = FOO
609
610 =item
611
612 Allow for scientific notation. (TT3)
613
614 [% a = 1.2e-20 %]
615
616 [% 123.fmt('%.3e') %] # = 1.230e+02
617
618 =item
619
620 Allow for hexidecimal input. (TT3)
621
622 [% a = 0xff0000 %][% a %] # = 16711680
623
624 [% a = 0xff2 / 0xd; a.fmt('%x') %] # = 13a
625
626 =item
627
628 FOREACH variables can be nested.
629
630 [% FOREACH f.b = [1..10] ; f.b ; END %]
631
632 Note that nested variables are subject to scoping issues.
633 f.b will not be reset to its value before the FOREACH.
634
635 =item
636
637 Post operative directives can be nested. (TT3)
638
639 Andy Wardley calls this side-by-side effect notation.
640
641 [% one IF two IF three %]
642
643 same as
644
645 [% IF three %][% IF two %][% one %][% END %][% END %]
646
647
648 [% a = [[1..3], [5..7]] %][% i FOREACH i = j FOREACH j = a %] # = 123567
649
650 =item
651
652 Semi-colons on directives in the same tag are optional. (TT3)
653
654 [% SET a = 1
655 GET a
656 %]
657
658 [% FOREACH i = [1 .. 10]
659 i
660 END %]
661
662 Note: a semi-colon is still required in front of any block directive
663 that can be used as a post-operative directive.
664
665 [% 1 IF 0
666 2 %] # prints 2
667
668 [% 1; IF 0
669 2
670 END %] # prints 1
671
672 Note2: This behavior can be disabled by setting the SEMICOLONS
673 configuration item to a true value. If SEMICOLONS is true, then
674 a SEMICOLON must be set after any directive that isn't followed
675 by a post-operative directive.
676
677 =item
678
679 CATCH blocks can be empty.
680
681 TT2 requires them to contain something.
682
683 =item
684
685 Added a DUMP directive.
686
687 Used for Data::Dumpering the passed variable or expression.
688
689 [% DUMP a.a %]
690
691 =item
692
693 Added CONFIG directive.
694
695 [% CONFIG
696 ANYCASE => 1
697 PRE_CHOMP => '-'
698 %]
699
700 =item
701
702 Configuration options can use lowercase names instead
703 of the all uppercase names that TT2 uses.
704
705 my $t = CGI::Ex::Template->new({
706 anycase => 1,
707 interpolate => 1,
708 });
709
710 =item
711
712 Added LOOP directive (works the same as LOOP in HTML::Template.
713
714 [%- var = [{key => 'a'}, {key => 'b'}] %]
715 [%- LOOP var %]
716 ([% key %])
717 [%- END %]
718
719 Prints
720
721 (a)
722 (b)
723
724 =item
725
726 CET can parse HTML::Template and HTML::Template::Expr documents
727 as well as TT2 and TT3 documents.
728
729 =item
730
731 Added SYNTAX configuration. The SYNTAX configuration can be
732 used to change what template syntax will be used for parsing
733 included templates or eval'ed strings.
734
735 [% CONFIG SYNTAX => 'hte' %]
736 [% var = '<TMPL_VAR EXPR="sprintf('%s', 'hello world')">' %]
737 [% var | eval %]
738
739 =item
740
741 CET does not generate Perl code.
742
743 It generates an "opcode" tree. The opcode tree is an arrayref
744 of scalars and array refs nested as deeply as possible. This "simple"
745 structure could be shared TT implementations in other languages
746 via JSON or YAML.
747
748 =item
749
750 CET uses storable for its compiled templates.
751
752 If EVAL_PERL is off, CET will not eval_string on ANY piece of information.
753
754 =item
755
756 There is eval_filter and MACRO recursion protection
757
758 You can control the nested nature of eval_filter and MACRO
759 recursion using the MAX_EVAL_RECURSE and MAX_MACRO_RECURSE
760 configuration items.
761
762 =item
763
764 There is no context.
765
766 CET provides a context object that mimics the Template::Context
767 interface for use by some TT filters, eval perl blocks, views,
768 and plugins.
769
770 =item
771
772 There is no stash.
773
774 Well there is but it isn't an object.
775
776 CET only supports the variables passed in VARIABLES, PRE_DEFINE, and
777 those passed to the process method. CET provides a stash object that
778 mimics the Template::Stash interface for use by some TT filters, eval
779 perl blocks, and plugins.
780
781 =item
782
783 There is no provider.
784
785 CET uses the load_parsed_tree method to get and cache templates.
786
787 =item
788
789 There is no parser/grammar.
790
791 CET has its own built-in recursive regex based parser and grammar system.
792
793 CET can actually be substituted in place of the native Template::Parser and
794 Template::Grammar in TT by using the Template::Parser::CET module. This
795 module uses the output of parse_tree to generate a TT style compiled perl
796 document.
797
798 =item
799
800 The DEBUG directive is more limited.
801
802 It only understands DEBUG_DIRS (8) and DEBUG_UNDEF (2).
803
804 =item
805
806 CET has better line information
807
808 When debug dirs is on, directives on different lines separated
809 by colons show the line they are on rather than a general line range.
810
811 Parse errors actually know what line and character they occured at.
812
813 =back
814
815 =head1 HOW IS CGI::Ex::Template DIFFERENT from HTML::Template
816
817 CET can use the same base template syntax and configuration items as HTE
818 and HT. The internals of CET were written to support TT3, but were
819 general enough to be extended to support HTML::Template as well. The result
820 is HTML::Template::Expr compatible syntax, with CET speed and a wide range
821 of additional features.
822
823 The TMPL_VAR, TMPL_IF, TMPL_ELSE, TMPL_UNLESS, TMPL_LOOP, and TMPL_INCLUDE
824 all work identically to HTML::Template.
825
826 =over 4
827
828 =item
829
830 Added support for other TT3 directives and for TT style "dot notation."
831
832 <TMPL_SET a = "bar">
833 <TMPL_SET b = [1 .. 25]>
834 <TMPL_SET foo = PROCESS 'filename.tt'>
835
836 <TMPL_GET foo> # similar to <TMPL_VAR NAME="foo">
837 <TMPL_GET b.3>
838 <TMPL_GET my.nested.chained.variable.1>
839 <TMPL_GET my_var | html>
840
841 <TMPL_USE foo = DBI(db => ...)>
842 <TMPL_CALL foo.connect>
843
844 Any of the TT directives can be used in HTML::Template documents.
845
846 For many die-hard HTML::Template fans, it is probably quite scary to
847 be providing all of the TT functionality. All of the extended
848 TT functionality can be disabled by setting the NO_TT configuration
849 item. The NO_TT configuration is automatically set if the SYNTAX is
850 set to "ht" and the output method is called.
851
852 =item
853
854 There is an ELSIF!!!
855
856 <TMPL_IF foo>
857 FOO
858 <TMPL_ELSIF bar>
859 BAR
860 <TMPL_ELSE>
861 Done then
862 </TMPL_IF>
863
864 =item
865
866 Added CHOMP capabilities (PRE_CHOMP and POST_CHOMP)
867
868 Foo
869 <~TMPL_VAR EXPR="1+2"~>
870 Bar
871
872 Prints Foo3Bar
873
874 =item
875
876 Added INTERPOLATE capability
877
878 <TMPL_SET foo = 'FOO'>
879 <TMPL_CONFIG INTERPOLATE => 1>
880 $foo <TMPL_GET foo> ${ 1 + 2 }
881
882 Prints
883
884 FOO FOO 3
885
886 =item
887
888 Allow for HTML::Template templates to include TT style templates.
889
890 <TMPL_CONFIG SYNTAX => 'tt3'>
891 <TMPL_INCLUDE "filename.tt">
892
893 =item
894
895 Allow for Expr parsing to follow proper precedence rules.
896
897 <TMPL_VAR EXPR="1 + 2 * 3">
898
899 Properly prints 7.
900
901 =item
902
903 Uses all of the caching and opcode tree optimations provided by
904 CGI::Ex::Template and CGI::Ex::Template::XS.
905
906 =item
907
908 CET does not provide the query method from HTML::Template. This
909 is because parsing of the document is delayed until the output
910 method is called, and because CET supports TT style chained
911 variables which often are not resolvable until run time.
912
913 =back
914
915 =head1 VARIABLES
916
917 This section discusses how to use variables and expressions in the TT
918 mini-language.
919
920 A variable is the most simple construct to insert into the TT mini
921 language. A variable name will look for the matching value inside
922 CGI::Ex::Templates internal stash of variables which is essentially a
923 hash reference. This stash is initially populated by either passing a
924 hashref as the second argument to the process method, or by setting
925 the "VARIABLES" or "PRE_DEFINE" configuration variables.
926
927 If you are using the HT and HTE syntaxes, the VAR, IF, UNLESS,
928 LOOP, and INCLUDE directives will accept a NAME attribute which may
929 only be a single level (non-chained) HTML::Template variable name, or
930 they may accept an EXPR attribute which may be any valid TT3 variable or expression.
931
932 The following are some sample ways to access variables.
933
934 ### some sample variables
935 my %vars = (
936 one => '1.0',
937 foo => 'bar',
938 vname => 'one',
939 some_code => sub { "You passed me (".join(', ', @_).")" },
940 some_data => {
941 a => 'A',
942 bar => 3234,
943 c => [3, 1, 4, 1, 5, 9],
944 vname => 'one',
945 },
946 my_list => [20 .. 50],
947 cet => CGI::Ex::Template->new,
948 );
949
950 ### pass the variables into the CET process
951 $cet->process($template_name, \%vars)
952 || die $cet->error;
953
954 ### pass the variables during object creation (will be available to every process call)
955 my $cet = CGI::Ex::Template->new(VARIABLES => \%vars);
956
957 =head2 GETTING VARIABLES
958
959 Once you have variables defined, they can be used directly in the
960 template by using their name in the stash. Or by using the GET
961 directive.
962
963 [% foo %]
964 [% one %]
965 [% GET foo %]
966
967 Would print when processed:
968
969 bar
970 1.0
971 bar
972
973 To access members of a hashref or an arrayref, you can chain together
974 the names using a ".".
975
976 [% some_data.a %]
977 [% my_list.0] [% my_list.1 %] [% my_list.-1 %]
978 [% some_data.c.2 %]
979
980 Would print:
981
982 A
983 20 21 50
984 4
985
986 If the value of a variable is a code reference, it will be called.
987 You can add a set of parenthesis and arguments to pass arguments.
988 Arguments are variables and can be as complex as necessary.
989
990 [% some_code %]
991 [% some_code() %]
992 [% some_code(foo) %]
993 [% some_code(one, 2, 3) %]
994
995 Would print:
996
997 You passed me ().
998 You passed me ().
999 You passed me (bar).
1000 You passed me (1.0, 2, 3).
1001
1002 If the value of a variable is an object, methods can be called using
1003 the "." operator.
1004
1005 [% cet %]
1006
1007 [% cet.dump_parse_expr('1 + 2').replace('\s+', ' ') %]
1008
1009 Would print something like:
1010
1011 CGI::Ex::Template=HASH(0x814dc28)
1012
1013 $VAR1 = [ [ undef, '+', '1', '2' ], 0 ];
1014
1015 Each type of data (string, array and hash) have virtual methods
1016 associated with them. Virtual methods allow for access to functions
1017 that are commonly used on those types of data. For the full list of
1018 built in virtual methods, please see the section titled VIRTUAL
1019 METHODS
1020
1021 [% foo.length %]
1022 [% my_list.size %]
1023 [% some_data.c.join(" | ") %]
1024
1025 Would print:
1026
1027 3
1028 31
1029 3 | 1 | 4 | 5 | 9
1030
1031 It is also possible to "interpolate" variable names using a "$". This
1032 allows for storing the name of a variable inside another variable. If
1033 a variable name is a little more complex it can be embedded inside of
1034 "${" and "}".
1035
1036 [% $vname %]
1037 [% ${vname} %]
1038 [% ${some_data.vname} %]
1039 [% some_data.$foo %]
1040 [% some_data.${foo} %]
1041
1042 Would print:
1043
1044 1.0
1045 1.0
1046 1.0
1047 3234
1048 3234
1049
1050 In CET it is also possible to embed any expression (non-directive) in
1051 "${" and "}" and it is possible to use non-integers for array access.
1052 (This is not available in TT2)
1053
1054 [% ['a'..'z'].${ 2.3 } %]
1055 [% {ab => 'AB'}.${ 'a' ~ 'b' } %]
1056 [% color = qw/Red Blue/; FOR [1..4] ; color.${ loop.index % color.size } ; END %]
1057
1058 Would print:
1059
1060 c
1061 AB
1062 RedBlueRedBlue
1063
1064 =head2 SETTING VARIABLES.
1065
1066 To define variables during processing, you can use the = operator. In
1067 most cases this is the same as using the SET directive.
1068
1069 [% a = 234 %][% a %]
1070 [% SET b = "Hello" %][% b %]
1071
1072 Would print:
1073
1074 234
1075 Hello
1076
1077 It is also possible to create arrayrefs and hashrefs.
1078
1079 [% a = [1, 2, 3] %]
1080 [% b = {key1 => 'val1', 'key2' => 'val2'} %]
1081
1082 [% a.1 %]
1083 [% b.key1 %] [% b.key2 %]
1084
1085 Would print:
1086
1087 2
1088 val1 val2
1089
1090 It is possible to set multiple values in the same SET directive.
1091
1092 [% SET a = 'A'
1093 b = 'B'
1094 c = 'C' %]
1095 [% a %] [% b %] [% c %]
1096
1097 Would print:
1098
1099 A B C
1100
1101 It is also possible to unset variables, or to set members of
1102 nested data structures.
1103
1104 [% a = 1 %]
1105 [% SET a %]
1106
1107 [% b.0.c = 37 %]
1108
1109 ([% a %])
1110 [% b.0.c %]
1111
1112 Would print
1113
1114 ()
1115 37
1116
1117 =head1 LITERALS AND CONSTRUCTORS
1118
1119 The following are the types of literals (numbers and strings) and
1120 constructors (hash and array constructs) allowed in CET. They can be
1121 used as arguments to functions, in place of variables in directives,
1122 and in place of variables in expressions. In CET it is also possible
1123 to call virtual methods on literal values.
1124
1125 =over 4
1126
1127 =item Integers and Numbers.
1128
1129 [% 23423 %] Prints an integer.
1130 [% 3.14159 %] Prints a number.
1131 [% pi = 3.14159 %] Sets the value of the variable.
1132 [% 3.13159.length %] Prints 7 (the string length of the number)
1133
1134 Scientific notation is supported.
1135
1136 [% 314159e-5 + 0 %] Prints 3.14159.
1137
1138 [% .0000001.fmt('%.1e') %] Prints 1.0e-07
1139
1140 Hexidecimal input is also supported.
1141
1142 [% 0xff + 0 %] Prints 255
1143
1144 [% 48875.fmt('%x') %] Prints beeb
1145
1146 =item Single quoted strings.
1147
1148 Returns the string. No variable interpolation happens.
1149
1150 [% 'foobar' %] Prints "foobar".
1151 [% '$foo\n' %] Prints "$foo\\n". # the \\n is a literal "\" and an "n"
1152 [% 'That\'s nice' %] Prints "That's nice".
1153 [% str = 'A string' %] Sets the value of str.
1154 [% 'A string'.split %] Splits the string on ' ' and returns the list.
1155
1156 Note: virtual methods can only be used on literal strings in CET, not in TT.
1157
1158 You may also embed the current tags in strings (CET only).
1159
1160 [% '[% 1 + 2 %]' | eval %] Prints "3"
1161
1162 =item Double quoted strings.
1163
1164 Returns the string. Variable interpolation happens.
1165
1166 [% "foobar" %] Prints "foobar".
1167 [% "$foo" %] Prints "bar" (assuming the value of foo is bar).
1168 [% "${foo}" %] Prints "bar" (assuming the value of foo is bar).
1169 [% "foobar\n" %] Prints "foobar\n". # the \n is a newline.
1170 [% str = "Hello" %] Sets the value of str.
1171 [% "foo".replace('foo','bar') %] Prints "bar".
1172
1173 Note: virtual methods can only be used on literal strings in CET, not in TT.
1174
1175 You may also embed the current tags in strings (CET only).
1176
1177 [% "[% 1 + 2 %]" | eval %] Prints "3"
1178
1179 =item Array Constructs.
1180
1181 [% [1, 2, 3] %] Prints something like ARRAY(0x8309e90).
1182 [% array1 = [1 .. 3] %] Sets the value of array1.
1183 [% array2 = [foo, 'a', []] %] Sets the value of array2.
1184 [% [4, 5, 6].size %] Prints 3.
1185 [% [7, 8, 9].reverse.0 %] Prints 9.
1186
1187 Note: virtual methods can only be used on array contructs in CET, not in TT.
1188
1189 =item Quoted Array Constructs.
1190
1191 [% qw/1 2 3/ %] Prints something like ARRAY(0x8309e90).
1192 [% array1 = qw{Foo Bar Baz} %] Sets the value of array1.
1193 [% qw[4 5 6].size %] Prints 3.
1194 [% qw(Red Blue).reverse.0 %] Prints Blue.
1195
1196 Note: this works in CET and is planned for TT3.
1197
1198 =item Hash Constructs.
1199
1200 [% {foo => 'bar'} %] Prints something like HASH(0x8305880)
1201 [% hash = {foo => 'bar', c => {}} %] Sets the value of hash.
1202 [% {a => 'A', b => 'B'}.size %] Prints 2.
1203 [% {'a' => 'A', 'b' => 'B'}.size %] Prints 2.
1204 [% name = "Tom" %]
1205 [% {Tom => 'You are Tom',
1206 Kay => 'You are Kay'}.$name %] Prints You are Tom
1207
1208 Note: virtual methods can only be used on hash contructs in CET, not in TT.
1209
1210 =item Regex Constructs.
1211
1212 [% /foo/ %] Prints (?-xism:foo)
1213 [% a = /(foo)/i %][% "FOO".match(a).0 %] Prints FOO
1214
1215 Note: this works in CET and is planned for TT3.
1216
1217 =head1 EXPRESSIONS
1218
1219 Expressions are one or more variables or literals joined together with
1220 operators. An expression can be used anywhere a variable can be used
1221 with the exception of the variable name in the SET directive, and the
1222 filename of PROCESS, INCLUDE, WRAPPER, and INSERT.
1223
1224 The following section shows some samples of expressions. For a full
1225 list of available operators, please see the section titled OPERATORS.
1226
1227 [% 1 + 2 %] Prints 3
1228 [% 1 + 2 * 3 %] Prints 7
1229 [% (1 + 2) * 3 %] Prints 9
1230
1231 [% x = 2 %] # assignments don't return anything
1232 [% (x = 2) %] Prints 2 # unless they are in parens
1233 [% y = 3 %]
1234 [% x * (y - 1) %] Prints 4
1235
1236 =head1 VIRTUAL METHODS
1237
1238 The following is the list of builtin virtual methods and filters that
1239 can be called on each type of data.
1240
1241 In CGI::Ex::Template, the "|" operator can be used to call virtual
1242 methods just the same way that the "." operator can. The main
1243 difference between the two is that on access to hashrefs or objects,
1244 the "|" means to always call the virtual method or filter rather than
1245 looking in the hashref for a key by that name, or trying to call that
1246 method on the object. This is similar to how TT3 will function.
1247
1248 Virtual methods are also made available via Virtual Objects which
1249 are discussed in a later section.
1250
1251 =head2 SCALAR VIRTUAL METHODS AND FILTERS
1252
1253 The following is the list of builtin virtual methods and filters that
1254 can be called on scalar data types. In CET and TT3, filters and
1255 virtual methods are more closely related than in TT2. In general
1256 anywhere a virtual method can be used a filter can be used also - and
1257 likewise all scalar virtual methods can be used as filters.
1258
1259 In addition to the filters listed below, CET will automatically load
1260 Template::Filters and use them if Template::Toolkit is installed.
1261
1262 In addition to the scalar virtual methods, any scalar will be
1263 automatically converted to a single item list if a list virtual method
1264 is called on it.
1265
1266 Scalar virtual methods are also available through the "Text" virtual
1267 object (except for true filters such as eval and redirect).
1268
1269 All scalar virtual methods are available as top level functions as well.
1270 This is not true of TT2. In CGI::Ex::Template the following are equivalent:
1271
1272 [% "abc".length %]
1273 [% length("abc") %]
1274
1275 You may set VMETHOD_FUNCTIONS to 0 to disable this behavior.
1276
1277 =over 4
1278
1279 =item '0'
1280
1281 [% item = 'foo' %][% item.0 %] Returns foo.
1282
1283 Allows for scalars to mask as arrays (scalars already will, but this
1284 allows for more direct access).
1285
1286 =item abs
1287
1288 [% -1.abs %] Returns the absolute value
1289
1290 =item atan2
1291
1292 [% pi = 4 * 1.atan2(1) %]
1293
1294 Returns the arctangent. The item itself represents Y, the passed argument represents X.
1295
1296 =item chunk
1297
1298 [% item.chunk(60).join("\n") %] Split string up into a list of chunks of text 60 chars wide.
1299
1300 =item collapse
1301
1302 [% item.collapse %] Strip leading and trailing whitespace and collapse all other space to one space.
1303
1304 =item cos
1305
1306 [% item.cos %] Returns the cosine of the item.
1307
1308 =item defined
1309
1310 [% item.defined %] Always true - because the undef sub translates all undefs to ''.
1311
1312 =item eval
1313
1314 [% item.eval %]
1315
1316 Process the string as though it was a template. This will start the parsing
1317 engine and will use the same configuration as the current process. CET is several times
1318 faster at doing this than TT is and is considered acceptable.
1319
1320 This is a filter and is not available via the Text virtual object.
1321
1322 =item evaltt
1323
1324 Same as the eval filter.
1325
1326 =item exp
1327
1328 [% 1.exp %] Something like 2.71828182845905
1329
1330 Returns "e" to the power of the item.
1331
1332 =item file
1333
1334 Same as the redirect filter.
1335
1336 =item fmt
1337
1338 [% item.fmt('%d') %]
1339 [% item.fmt('%6s') %]
1340 [% item.fmt('%*s', 6) %]
1341
1342 Similar to format. Returns a string formatted with the passed pattern. Default pattern is %s.
1343 Opposite from of the sprintf vmethod.
1344
1345 =item format
1346
1347 [% item.format('%d') %]
1348 [% item.format('%6s') %]
1349 [% item.format('%*s', 6) %]
1350
1351 Print the string out in the specified format. It is similar to
1352 the "fmt" virtual method, except that the item is split on newline and each line is
1353 processed separately.
1354
1355 =item hash
1356
1357 [% item.hash %] Returns a one item hash with a key of "value" and a value of the item.
1358
1359
1360 =item hex
1361
1362 [% "FF".hex %]
1363
1364 Returns the decimal value of the passed hex numbers. Note that you
1365 may also just use [% 0xFF %].
1366
1367 =item html
1368
1369 [% item.html %] Performs a very basic html encoding (swaps out &, <, > and " for the html entities)
1370
1371 =item indent
1372
1373 [% item.indent(3) %] Indent that number of spaces.
1374
1375 [% item.indent("Foo: ") %] Add the string "Foo: " to the beginning of every line.
1376
1377 =item int
1378
1379 [% item.int %] Return the integer portion of the value (0 if none).
1380
1381 =item lc
1382
1383 Same as the lower vmethod. Returns the lower cased version of the item.
1384
1385 =item lcfirst
1386
1387 [% item.lcfirst %] Capitalize the leading letter.
1388
1389 =item length
1390
1391 [% item.length %] Return the length of the string.
1392
1393 =item list
1394
1395 [% item.list %] Returns a list with a single value of the item.
1396
1397 =item log
1398
1399 [% 8.exp.log %] Equal to 8.
1400
1401 Returns the natural log base "e" of the item.
1402
1403 =item lower
1404
1405 [% item.lower %] Return a lower-casified string.
1406
1407 =item match
1408
1409 [% item.match("(\w+) (\w+)") %] Return a list of items matching the pattern.
1410
1411 [% item.match("(\w+) (\w+)", 1) %] Same as before - but match globally.
1412
1413 In CGI::Ex::Template and TT3 you can use regular expressions notation as well.
1414
1415 [% item.match( /(\w+) (\w+)/ ) %] Same as before.
1416
1417 [% item.match( m{(\w+) (\w+)} ) %] Same as before.
1418
1419 =item null
1420
1421 [% item.null %] Do nothing.
1422
1423 =item oct
1424
1425 [% "377".oct %]
1426
1427 Returns the decimal value of the octal string. On recent versions of perl you
1428 may also pass numbers starting with 0x which will be interpreted as hexidecimal,
1429 and starting with 0b which will be interpreted as binary.
1430
1431 =item rand
1432
1433 [% item = 10; item.rand %] Returns a number greater or equal to 0 but less than 10.
1434 [% 1.rand %]
1435
1436 Note: This filter is not available as of TT2.15.
1437
1438 =item remove
1439
1440 [% item.remove("\s+") %] Same as replace - but is global and replaces with nothing.
1441
1442 =item redirect
1443
1444 [% item.redirect("output_file.html") %]
1445
1446 Writes the contents out to the specified file. The filename
1447 must be relative to the OUTPUT_PATH configuration variable and the OUTPUT_PATH variable must be set.
1448
1449 This is a filter and is not available via the Text virtual object.
1450
1451 =item repeat
1452
1453 [% item.repeat(3) %] Repeat the item 3 times
1454
1455 [% item.repeat(3, ' | ') %] Repeat the item 3 times separated with ' | '
1456
1457 =item replace
1458
1459 [% item.replace("\s+", "&nbsp;") %] Globally replace all space with &nbsp;
1460
1461 [% item.replace("foo", "bar", 0) %] Replace only the first instance of foo with bar.
1462
1463 [% item.replace("(\w+)", "($1)") %] Surround all words with parenthesis.
1464
1465 In CGI::Ex::Template and TT3 you may also use normal regular expression notation.
1466
1467 [% item.replace(/(\w+)/, "($1)") %] Same as before.
1468
1469 =item search
1470
1471 [% item.search("(\w+)") %] Tests if the given pattern is in the string.
1472
1473 In CGI::Ex::Template and TT3 you may also use normal regular expression notation.
1474
1475 [% item.search(/(\w+)/, "($1)") %] Same as before.
1476
1477 =item sin
1478
1479 [% item.sin %] Returns the sine of the item.
1480
1481 =item size
1482
1483 [% item.size %] Always returns 1.
1484
1485 =item split
1486
1487 [% item.split %] Returns an arrayref from the item split on " "
1488
1489 [% item.split("\s+") %] Returns an arrayref from the item split on /\s+/
1490
1491 [% item.split("\s+", 3) %] Returns an arrayref from the item split on /\s+/ splitting until 3 elements are found.
1492
1493 In CGI::Ex::Template and TT3 you may also use normal regular expression notation.
1494
1495 [% item.split( /\s+/, 3 ) %] Same as before.
1496
1497 =item sprintf
1498
1499 [% item = "%d %d" %]
1500 [% item.sprintf(7, 8) %]
1501
1502 Uses the pattern stored in self, and passes it to sprintf with the passed arguments.
1503 Opposite from the fmt vmethod.
1504
1505 =item sqrt
1506
1507 [% item.sqrt %]
1508
1509 Returns the square root of the number.
1510
1511 =item srand
1512
1513 Calls the perl srand function to set the interal random seed. This
1514 will affect future calls to the rand vmethod.
1515
1516 =item stderr
1517
1518 [% item.stderr %] Print the item to the current STDERR handle.
1519
1520 =item substr
1521
1522 [% item.substr(i) %] Returns a substring of item starting at i and going to the end of the string.
1523
1524 [% item.substr(i, n) %] Returns a substring of item starting at i and going n characters.
1525
1526 =item trim
1527
1528 [% item.trim %] Strips leading and trailing whitespace.
1529
1530 =item uc
1531
1532 Same as the upper command. Returns upper cased string.
1533
1534 =item ucfirst
1535
1536 [% item.ucfirst %] Lower-case the leading letter.
1537
1538 =item upper
1539
1540 [% item.upper %] Return a upper cased string.
1541
1542 =item uri
1543
1544 [% item.uri %] Perform a very basic URI encoding.
1545
1546 =item url
1547
1548 [% item.url %] Perform a URI encoding - but some characters such
1549 as : and / are left intact.
1550
1551 =back
1552
1553 =head2 LIST VIRTUAL METHODS
1554
1555 The following methods can be called on an arrayref type data structures (scalar
1556 types will automatically promote to a single element list and call these methods
1557 if needed):
1558
1559 Additionally, list virtual methods can be accessed via the List
1560 Virtual Object.
1561
1562 =over 4
1563
1564 =item fmt
1565
1566 [% mylist.fmt('%s', ', ') %]
1567 [% mylist.fmt('%6s', ', ') %]
1568 [% mylist.fmt('%*s', ', ', 6) %]
1569
1570 Passed a pattern and an string to join on. Returns a string of the values of the list
1571 formatted with the passed pattern and joined with the passed string.
1572 Default pattern is %s and the default join string is a space.
1573
1574 =item first
1575
1576 [% mylist.first(3) %] Returns a list of the first 3 items in the list.
1577
1578 =item grep
1579
1580 [% mylist.grep("^\w+\.\w+$") %] Returns a list of all items matching the pattern.
1581
1582 =item hash
1583
1584 [% mylist.hash %] Returns a hashref with the array indexes as keys and the values as values.
1585
1586 =item join
1587
1588 [% mylist.join %] Joins on space.
1589 [% mylist.join(", ") Joins on the passed argument.
1590
1591 =item last
1592
1593 [% mylist.last(3) %] Returns a list of the last 3 items in the list.
1594
1595 =item list
1596
1597 [% mylist.list %] Returns a reference to the list.
1598
1599 =item max
1600
1601 [% mylist.max %] Returns the last item in the array.
1602
1603 =item merge
1604
1605 [% mylist.merge(list2) %] Returns a new list with all defined items from list2 added.
1606
1607 =item nsort
1608
1609 [% mylist.nsort %] Returns the numerically sorted items of the list. If the items are
1610 hashrefs, a key containing the field to sort on can be passed.
1611
1612 =item pop
1613
1614 [% mylist.pop %] Removes and returns the last element from the arrayref (the stash is modified).
1615
1616 =item push
1617
1618 [% mylist.push(23) %] Adds an element to the end of the arrayref (the stash is modified).
1619
1620 =item pick
1621
1622 [% mylist.pick %] Returns a random item from the list.
1623 [% ['a' .. 'z'].pick %]
1624
1625 An additional numeric argument is how many items to return.
1626
1627 [% ['a' .. 'z'].pick(8).join('') %]
1628
1629 Note: This filter is not available as of TT2.15.
1630
1631 =item reverse
1632
1633 [% mylist.reverse %] Returns the list in reverse order.
1634
1635 =item shift
1636
1637 [% mylist.shift %] Removes and returns the first element of the arrayref (the stash is modified).
1638
1639 =item size
1640
1641 [% mylist.size %] Returns the number of elements in the array.
1642
1643 =item slice
1644
1645 [% mylist.slice(i, n) %] Returns a list from the arrayref beginning at index i and continuing for n items.
1646
1647 =item sort
1648
1649 [% mylist.sort %] Returns the alphabetically sorted items of the list. If the items are
1650 hashrefs, a key containing the field to sort on can be passed.
1651
1652 =item splice
1653
1654 [% mylist.splice(i, n) %] Removes items from array beginning at i and continuing for n items.
1655
1656 [% mylist.splice(i, n, list2) %] Same as before, but replaces removed items with the items
1657 from list2.
1658
1659 =item unique
1660
1661 [% mylist.unique %] Return a list of the unique items in the array.
1662
1663 =item unshift
1664
1665 [% mylist.unshift(23) %] Adds an item to the beginning of the arrayref.
1666
1667 =back 4
1668
1669 =head2 HASH VIRTUAL METHODS
1670
1671 The following methods can be called on hash type data structures:
1672
1673 Additionally, list virtual methods can be accessed via the Hash
1674 Virtual Object.
1675
1676 =over 4
1677
1678 =item fmt
1679
1680 [% myhash.fmt('%s => %s', "\n") %]
1681 [% myhash.fmt('%4s => %5s', "\n") %]
1682 [% myhash.fmt('%*s => %*s', "\n", 4, 5) %]
1683
1684 Passed a pattern and an string to join on. Returns a string of the key/value pairs
1685 of the hash formatted with the passed pattern and joined with the passed string.
1686 Default pattern is "%s\t%s" and the default join string is a newline.
1687
1688 =item defined
1689
1690 [% myhash.defined('a') %] Checks if a is defined in the hash.
1691
1692 =item delete
1693
1694 [% myhash.delete('a') %] Deletes the item from the hash.
1695
1696 Unlink Perl the value is not returned. Multiple values may be passed
1697 and represent the keys to be deleted.
1698
1699 =item each
1700
1701 [% myhash.each.join(", ") %] Turns the contents of the hash into a list - subject
1702 to change as TT is changing the operations of each and list.
1703
1704 =item exists
1705
1706 [% myhash.exists('a') %] Checks if a is in the hash.
1707
1708 =item hash
1709
1710 [% myhash.hash %] Returns a reference to the hash.
1711
1712 =item import
1713
1714 [% myhash.import(hash2) %] Overlays the keys of hash2 over the keys of myhash.
1715
1716 =item item
1717
1718 [% myhash.item(key) %] Returns the hashes value for that key.
1719
1720 =item items
1721
1722 [% myhash.items %] Returns a list of the key and values (flattened hash)
1723
1724 =item keys
1725
1726 [% myhash.keys.join(', ') %] Returns an arrayref of the keys of the hash.
1727
1728 =item list
1729
1730 [% myhash.list %] Returns an arrayref with the hash as a single value (subject to change).
1731
1732 =item pairs
1733
1734 [% myhash.pairs %] Returns an arrayref of hashrefs where each hash contains {key => $key, value => $value}
1735 for each value of the hash.
1736
1737 =item nsort
1738
1739 [% myhash.nsort.join(", ") %] Returns a numerically sorted list of the keys.
1740
1741 =item size
1742
1743 [% myhash.size %] Returns the number of key/value pairs in the hash.
1744
1745 =item sort
1746
1747 [% myhash.sort.join(", ") Returns an alphabetically sorted list.
1748
1749 =item values
1750
1751 [% myhash.values.join(', ') %] Returns an arrayref of the values of the hash.
1752
1753 =back
1754
1755 =head1 VIRTUAL OBJECTS
1756
1757 TT3 has a concept of Text, List, and Hash virtual objects which provide
1758 direct access to the scalar, list, and hash virtual methods. In the TT3
1759 engine this will allow for more concise generated code. Because CET does
1760 not generated perl code to be executed later, CET provides for these virtual
1761 objects but does so as more of a namespace (using the methods does not
1762 provide a speed optimization in your template - just may help clarify things).
1763
1764 [% a = "foo"; a.length %] => 3
1765
1766 [% a = "foo"; Text.length(a) %] => 3
1767
1768 [% a = Text.new("foo"); a.length %] => 3
1769
1770
1771 [% a = [1 .. 30]; a.size %] => 30
1772
1773 [% a = [1 .. 30]; List.size(a) %] => 30
1774
1775 [% a = List.new(1 .. 30); a.size %] => 30
1776
1777
1778 [% a = {a => 1, b => 2}; a.size %] => 2
1779
1780 [% a = {a => 1, b => 2}; Hash.size(a) %] => 2
1781
1782 [% a = Hash.new({a => 1, b => 2}); a.size %] => 2
1783
1784 [% a = Hash.new(a => 1, b => 2); a.size %] => 2
1785
1786 [% a = Hash.new(a = 1, b = 2); a.size %] => 2
1787
1788 [% a = Hash.new('a', 1, 'b', 2); a.size %] => 2
1789
1790 One limitation is that if you pass a key named "Text",
1791 "List", or "Hash" in your variable stash - the corresponding
1792 virtual object will be hidden.
1793
1794 Additionally, you can use all of the Virtual object methods with
1795 the pipe operator.
1796
1797 [% {a => 1, b => 2}
1798 | Hash.keys
1799 | List.join(", ") %] => a, b
1800
1801 Again, there aren't any speed optimizations to using the virtual
1802 objects in CET, but it can help clarify the intent in some cases.
1803
1804 Note: these aren't really objects. All of the "virtual objects" are
1805 references to the $SCALAR_OPS, $LIST_OPS, and $HASH_OPS hashes
1806 found in the $VOBJS hash of CGI::Ex::Template.
1807
1808 =head1 DIRECTIVES (TT Style)
1809
1810 This section contains the alphabetical list of DIRECTIVES available in
1811 the TT language. DIRECTIVES are the "functions" and control
1812 structures of the Template Toolkit mini-language. For further
1813 discussion and examples beyond what is listed below, please refer to
1814 the TT directives documentation.
1815
1816 [% IF 1 %]One[% END %]
1817 [% FOREACH a = [1 .. 3] %]
1818 a = [% a %]
1819 [% END %]
1820
1821 [% SET a = 1 %][% SET a = 2 %][% GET a %]
1822
1823 Multiple directives can be inside the same set of '[%' and '%]' tags
1824 as long as they are separated by space or semi-colons (;). Any block
1825 directive that can also be used as a post-operative directive (such as
1826 IF, WHILE, FOREACH, UNLESS, FILTER, and WRAPPER) must be separated
1827 from preceding directives with a semi-colon if it is being used as a
1828 block directive. It is more safe to always use a semi-colon. Note:
1829 separating by space is only available in CET but is a planned TT3
1830 feature.
1831
1832 [% SET a = 1 ; SET a = 2 ; GET a %]
1833 [% SET a = 1
1834 SET a = 2
1835 GET a
1836 %]
1837
1838 [% GET 1
1839 IF 0 # is a post-operative
1840 GET 2 %] # prints 2
1841
1842 [% GET 1;
1843 IF 0 # it is block based
1844 GET 2
1845 END
1846 %] # prints 1
1847
1848 The following is the list of directives.
1849
1850 =over 4
1851
1852 =item C<BLOCK>
1853
1854 Saves a block of text under a name for later use in PROCESS, INCLUDE,
1855 and WRAPPER directives. Blocks may be placed anywhere within the
1856 template being processed including after where they are used.
1857
1858 [% BLOCK foo %]Some text[% END %]
1859 [% PROCESS foo %]
1860
1861 Would print
1862
1863 Some text
1864
1865 [% INCLUDE foo %]
1866 [% BLOCK foo %]Some text[% END %]
1867
1868 Would print
1869
1870 Some text
1871
1872 Anonymous BLOCKS can be used for capturing.
1873
1874 [% a = BLOCK %]Some text[% END %][% a %]
1875
1876 Would print
1877
1878 Some text
1879
1880 Anonymous BLOCKS can be used with macros.
1881
1882
1883 =item C<BREAK>
1884
1885 Alias for LAST. Used for exiting FOREACH and WHILE loops.
1886
1887 =item C<CALL>
1888
1889 Calls the variable (and any underlying coderefs) as in the GET method, but
1890 always returns an empty string.
1891
1892 =item C<CASE>
1893
1894 Used with the SWITCH directive. See the L</"SWITCH"> directive.
1895
1896 =item C<CATCH>
1897
1898 Used with the TRY directive. See the L</"TRY"> directive.
1899
1900 =item C<CLEAR>
1901
1902 Clears any of the content currently generated in the innermost block
1903 or template. This can be useful when used in conjunction with the TRY
1904 statement to clear generated content if an error occurs later.
1905
1906 =item C<CONFIG>
1907
1908 Allow for changing the value of some compile time and runtime configuration
1909 options.
1910
1911 [% CONFIG
1912 ANYCASE => 1
1913 PRE_CHOMP => '-'
1914 %]
1915
1916 The following compile time configuration options may be set:
1917
1918 ANYCASE
1919 INTERPOLATE
1920 PRE_CHOMP
1921 POST_CHOMP
1922 V1DOLLAR
1923 V2PIPE
1924 V2EQUALS
1925
1926 The following runtime configuration options may be set:
1927
1928 DUMP
1929 VMETHOD_FUNCTIONS
1930
1931 If non-named parameters as passed, they will show the current configuration:
1932
1933 [% CONFIG ANYCASE, PRE_CHOMP %]
1934
1935 CONFIG ANYCASE = undef
1936 CONFIG PRE_CHOMP = undef
1937
1938 =item C<DEBUG>
1939
1940 Used to reset the DEBUG_FORMAT configuration variable, or to turn
1941 DEBUG statements on or off. This only has effect if the DEBUG_DIRS or
1942 DEBUG_ALL flags were passed to the DEBUG configuration variable.
1943
1944 [% DEBUG format '($file) (line $line) ($text)' %]
1945 [% DEBUG on %]
1946 [% DEBUG off %]
1947
1948 =item C<DEFAULT>
1949
1950 Similar to SET, but only sets the value if a previous value was not
1951 defined or was zero length.
1952
1953 [% DEFAULT foo = 'bar' %][% foo %] => 'bar'
1954
1955 [% foo = 'baz' %][% DEFAULT foo = 'bar' %][% foo %] => 'baz'
1956
1957 =item C<DUMP>
1958
1959 DUMP inserts a Data::Dumper printout of the variable or expression.
1960 If no argument is passed it will dump the entire contents of the
1961 current variable stash (with private keys removed).
1962
1963 The output also includes the current file and line number that the
1964 DUMP directive was called from.
1965
1966 See the DUMP configuration item for ways to customize and control
1967 the output available to the DUMP directive.
1968
1969 [% DUMP %] # dumps everything
1970
1971 [% DUMP 1 + 2 %]
1972
1973 =item C<ELSE>
1974
1975 Used with the IF directive. See the L</"IF"> directive.
1976
1977 =item C<ELSIF>
1978
1979 Used with the IF directive. See the L</"IF"> directive.
1980
1981 =item C<END>
1982
1983 Used to end a block directive.
1984
1985 =item C<FILTER>
1986
1987 Used to apply different treatments to blocks of text. It may operate as a BLOCK
1988 directive or as a post operative directive. CET supports all of the filters in
1989 Template::Filters. The lines between scalar virtual methods and filters is blurred (or
1990 non-existent) in CET. Anything that is a scalar virtual method may be used as a FILTER.
1991
1992 TODO - enumerate the at least 7 ways to pass and use filters.
1993
1994 =item C<'|'>
1995
1996 Alias for the FILTER directive. Note that | is similar to the
1997 '.' in CGI::Ex::Template. Therefore a pipe cannot be used directly after a
1998 variable name in some situations (the pipe will act only on that variable).
1999 This is the behavior employed by TT3. To get the TT2 behavior for a PIPE, use
2000 the V2PIPE configuration item.
2001
2002 =item C<FINAL>
2003
2004 Used with the TRY directive. See the L</"TRY"> directive.
2005
2006 =item C<FOR>
2007
2008 Alias for FOREACH
2009
2010 =item C<FOREACH>
2011
2012 Allows for iterating over the contents of any arrayref. If the variable is not an
2013 arrayref, it is automatically promoted to one.
2014
2015 [% FOREACH i IN [1 .. 3] %]
2016 The variable i = [% i %]
2017 [%~ END %]
2018
2019 [% a = [1 .. 3] %]
2020 [% FOREACH j IN a %]
2021 The variable j = [% j %]
2022 [%~ END %]
2023
2024 Would print:
2025
2026 The variable i = 1
2027 The variable i = 2
2028 The variable i = 3
2029
2030 The variable j = 1
2031 The variable j = 2
2032 The variable j = 3
2033
2034 You can also use the "=" instead of "IN" or "in".
2035
2036 [% FOREACH i = [1 .. 3] %]
2037 The variable i = [% i %]
2038 [%~ END %]
2039
2040 Same as before.
2041
2042 Setting into a variable is optional.
2043
2044 [% a = [1 .. 3] %]
2045 [% FOREACH a %] Hi [% END %]
2046
2047 Would print:
2048
2049 hi hi hi
2050
2051 If the item being iterated is a hashref and the FOREACH does not
2052 set into a variable, then values of the hashref are copied into
2053 the variable stash.
2054
2055 [% FOREACH [{a => 1}, {a => 2}] %]
2056 Key a = [% a %]
2057 [%~ END %]
2058
2059 Would print:
2060
2061 Key a = 1
2062 Key a = 2
2063
2064 The FOREACH process uses the CGI::Ex::Template::Iterator class to handle
2065 iterations (It is compatible with Template::Iterator). During the FOREACH
2066 loop an object blessed into the iterator class is stored in the variable "loop".
2067
2068 The loop variable provides the following information during a FOREACH:
2069
2070 index - the current index
2071 max - the max index of the list
2072 size - the number of items in the list
2073 count - index + 1
2074 number - index + 1
2075 first - true if on the first item
2076 last - true if on the last item
2077 next - return the next item in the list
2078 prev - return the previous item in the list
2079
2080 The following:
2081
2082 [% FOREACH [1 .. 3] %] [% loop.count %]/[% loop.size %] [% END %]
2083
2084 Would print:
2085
2086 1/3 2/3 3/3
2087
2088 The iterator is also available using a plugin. This allows for access
2089 to multiple "loop" variables in a nested FOREACH directive.
2090
2091 [%~ USE outer_loop = Iterator(["a", "b"]) %]
2092 [%~ FOREACH i = outer_loop %]
2093 [%~ FOREACH j = ["X", "Y"] %]
2094 [% outer_loop.count %]-[% loop.count %] = ([% i %] and [% j %])
2095 [%~ END %]
2096 [%~ END %]
2097
2098 Would print:
2099
2100 1-1 = (a and X)
2101 1-2 = (a and Y)
2102 2-1 = (b and X)
2103 2-2 = (b and Y)
2104
2105 FOREACH may also be used as a post operative directive.
2106
2107 [% "$i" FOREACH i = [1 .. 5] %] => 12345
2108
2109 =item C<GET>
2110
2111 Return the value of a variable or expression.
2112
2113 [% GET a %]
2114
2115 The GET keyword may be omitted.
2116
2117 [% a %]
2118
2119 [% 7 + 2 - 3 %] => 6
2120
2121 See the section on VARIABLES.
2122
2123 =item C<IF (IF / ELSIF / ELSE)>
2124
2125 Allows for conditional testing. Expects an expression as its only
2126 argument. If the expression is true, the contents of its block are
2127 processed. If false, the processor looks for an ELSIF block. If an
2128 ELSIF's expression is true then it is processed. Finally it looks for
2129 an ELSE block which is processed if none of the IF or ELSIF's
2130 expressions were true.
2131
2132 [% IF a == b %]A equaled B[% END %]
2133
2134 [% IF a == b -%]
2135 A equaled B
2136 [%- ELSIF a == c -%]
2137 A equaled C
2138 [%- ELSE -%]
2139 Couldn't determine that A equaled anything.
2140 [%- END %]
2141
2142 IF may also be used as a post operative directive.
2143
2144 [% 'A equaled B' IF a == b %]
2145
2146 Note: If you are using HTML::Template style documents, the TMPL_IF
2147 tag parses using the limited HTML::Template parsing rules. However,
2148 you may use EXPR="" to embed a TT3 style expression.
2149
2150 =item C<INCLUDE>
2151
2152 Parse the contents of a file or block and insert them. Variables defined
2153 or modifications made to existing variables are discarded after
2154 a template is included.
2155
2156 [% INCLUDE path/to/template.html %]
2157
2158 [% INCLUDE "path/to/template.html" %]
2159
2160 [% file = "path/to/template.html" %]
2161 [% INCLUDE $file %]
2162
2163 [% BLOCK foo %]This is foo[% END %]
2164 [% INCLUDE foo %]
2165
2166 Arguments may also be passed to the template:
2167
2168 [% INCLUDE "path/to/template.html" a = "An arg" b = "Another arg" %]
2169
2170 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
2171 or RELATIVE configuration items are set.
2172
2173 Multiple filenames can be passed by separating them with a plus, a space,
2174 or commas (TT2 doesn't support the comma). Any supplied arguments will
2175 be used on all templates.
2176
2177 [% INCLUDE "path/to/template.html",
2178 "path/to/template2.html" a = "An arg" b = "Another arg" %]
2179
2180 =item C<INSERT>
2181
2182 Insert the contents of a file without template parsing.
2183
2184 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
2185 or RELATIVE configuration items are set.
2186
2187 Multiple filenames can be passed by separating them with a plus, a space,
2188 or commas (TT2 doesn't support the comma).
2189
2190 [% INSERT "path/to/template.html",
2191 "path/to/template2.html" %]
2192
2193 =item C<LAST>
2194
2195 Used to exit out of a WHILE or FOREACH loop.
2196
2197 =item C<LOOP>
2198
2199 This directive operates similar to the HTML::Template loop directive.
2200 The LOOP directive expects a single variable name. This variable name
2201 should point to an arrayref of hashrefs. The keys of each hashref
2202 will be added to the variable stash when it is iterated.
2203
2204 [% var a = [{b => 1}, {b => 2}, {b => 3}] %]
2205
2206 [% LOOP a %] ([% b %]) [% END %]
2207
2208 Would print:
2209
2210 (1) (2) (3)
2211
2212 If CET is in HT mode and GLOBAL_VARS is false, the contents of
2213 the hashref will be the only items available during the loop iteration.
2214
2215 If LOOP_CONTEXT_VARS is true, and $QR_PRIVATE is false (default when
2216 called through the output method), then the variables __first__, __last__,
2217 __inner__, __odd__, and __counter__ will be set. See the HTML::Template
2218 loop_context_vars configuration item for more information.
2219
2220 =item C<MACRO>
2221
2222 Takes a directive and turns it into a variable that can take arguments.
2223
2224 [% MACRO foo(i, j) BLOCK %]You passed me [% i %] and [% j %].[% END %]
2225
2226 [%~ foo("a", "b") %]
2227 [% foo(1, 2) %]
2228
2229 Would print:
2230
2231 You passed me a and b.
2232 You passed me 1 and 2.
2233
2234 Another example:
2235
2236 [% MACRO bar(max) FOREACH i = [1 .. max] %]([% i %])[% END %]
2237
2238 [%~ bar(4) %]
2239
2240 Would print:
2241
2242 (1)(2)(3)(4)
2243
2244 =item C<META>
2245
2246 Used to define variables that will be available via either the
2247 template or component namespace.
2248
2249 Once defined, they cannot be overwritten.
2250
2251 [% template.foobar %]
2252 [%~ META foobar = 'baz' %]
2253 [%~ META foobar = 'bing' %]
2254
2255 Would print:
2256
2257 baz
2258
2259 =item C<NEXT>
2260
2261 Used to go to the next iteration of a WHILE or FOREACH loop.
2262
2263 =item C<PERL>
2264
2265 Only available if the EVAL_PERL configuration item is true (default is false).
2266
2267 Allow eval'ing the block of text as perl. The block will be parsed and then eval'ed.
2268
2269 [% a = "BimBam" %]
2270 [%~ PERL %]
2271 my $a = "[% a %]";
2272 print "The variable \$a was \"$a\"";
2273 $stash->set('b', "FooBar");
2274 [% END %]
2275 [% b %]
2276
2277 Would print:
2278
2279 The variable $a was "BimBam"
2280 FooBar
2281
2282 During execution, anything printed to STDOUT will be inserted into the template. Also,
2283 the $stash and $context variables are set and are references to objects that mimic the
2284 interface provided by Template::Context and Template::Stash. These are provided for
2285 compatibility only. $self contains the current CGI::Ex::Template object.
2286
2287 =item C<PROCESS>
2288
2289 Parse the contents of a file or block and insert them. Unlike INCLUDE,
2290 no variable localization happens so variables defined or modifications made
2291 to existing variables remain after the template is processed.
2292
2293 [% PROCESS path/to/template.html %]
2294
2295 [% PROCESS "path/to/template.html" %]
2296
2297 [% file = "path/to/template.html" %]
2298 [% PROCESS $file %]
2299
2300 [% BLOCK foo %]This is foo[% END %]
2301 [% PROCESS foo %]
2302
2303 Arguments may also be passed to the template:
2304
2305 [% PROCESS "path/to/template.html" a = "An arg" b = "Another arg" %]
2306
2307 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
2308 or RELATIVE configuration items are set.
2309
2310 Multiple filenames can be passed by separating them with a plus, a space,
2311 or commas (TT2 doesn't support the comma). Any supplied arguments will
2312 be used on all templates.
2313
2314 [% PROCESS "path/to/template.html",
2315 "path/to/template2.html" a = "An arg" b = "Another arg" %]
2316
2317 =item C<RAWPERL>
2318
2319 Only available if the EVAL_PERL configuration item is true (default is false).
2320 Similar to the PERL directive, but you will need to append
2321 to the $output variable rather than just calling PRINT.
2322
2323 =item C<RETURN>
2324
2325 Used to exit the innermost block or template and continue processing
2326 in the surrounding block or template.
2327
2328 =item C<SET>
2329
2330 Used to set variables.
2331
2332 [% SET a = 1 %][% a %] => "1"
2333 [% a = 1 %][% a %] => "1"
2334 [% b = 1 %][% SET a = b %][% a %] => "1"
2335 [% a = 1 %][% SET a %][% a %] => ""
2336 [% SET a = [1, 2, 3] %][% a.1 %] => "2"
2337 [% SET a = {b => 'c'} %][% a.b %] => "c"
2338
2339 =item C<STOP>
2340
2341 Used to exit the entire process method (out of all blocks and templates).
2342 No content will be processed beyond this point.
2343
2344 =item C<SWITCH>
2345
2346 Allow for SWITCH and CASE functionality.
2347
2348 [% a = "hi" %]
2349 [% b = "bar" %]
2350 [% SWITCH a %]
2351 [% CASE "foo" %]a was foo
2352 [% CASE b %]a was bar
2353 [% CASE ["hi", "hello"] %]You said hi or hello
2354 [% CASE DEFAULT %]I don't know what you said
2355 [% END %]
2356
2357 Would print:
2358
2359 You said hi or hello
2360
2361 =item C<TAGS>
2362
2363 Change the type of enclosing braces used to delineate template tags. This
2364 remains in effect until the end of the enclosing block or template or until
2365 the next TAGS directive. Either a named set of tags must be supplied, or
2366 two tags themselves must be supplied.
2367
2368 [% TAGS html %]
2369
2370 [% TAGS <!-- --> %]
2371
2372 The named tags are (duplicated from TT):
2373
2374 asp => ['<%', '%>' ], # ASP
2375 default => ['\[%', '%\]' ], # default
2376 html => ['<!--', '-->' ], # HTML comments
2377 mason => ['<%', '>' ], # HTML::Mason
2378 metatext => ['%%', '%%' ], # Text::MetaText
2379 php => ['<\?', '\?>' ], # PHP
2380 star => ['\[\*', '\*\]' ], # TT alternate
2381 template => ['\[%', '%\]' ], # Normal Template Toolkit
2382 template1 => ['[\[%]%', '%[%\]]'], # allow TT1 style
2383 tt2 => ['\[%', '%\]' ], # TT2
2384
2385 If custom tags are supplied, by default they are escaped using
2386 quotemeta. You may also pass explicitly quoted strings,
2387 or regular expressions as arguments as well (if your
2388 regex begins with a ', ", or / you must quote it.
2389
2390 [% TAGS [<] [>] %] matches "[<] tag [>]"
2391
2392 [% TAGS '[<]' '[>]' %] matches "[<] tag [>]"
2393
2394 [% TAGS "[<]" "[>]" %] matches "[<] tag [>]"
2395
2396 [% TAGS /[<]/ /[>]/ %] matches "< tag >"
2397
2398 [% TAGS ** ** %] matches "** tag **"
2399
2400 [% TAGS /**/ /**/ %] Throws an exception.
2401
2402 =item C<THROW>
2403
2404 Allows for throwing an exception. If the exception is not caught
2405 via the TRY DIRECTIVE, the template will abort processing of the directive.
2406
2407 [% THROW mytypes.sometime 'Something happened' arg1 => val1 %]
2408
2409 See the TRY directive for examples of usage.
2410
2411 =item C<TRY>
2412
2413 The TRY block directive will catch exceptions that are thrown
2414 while processing its block (It cannot catch parse errors unless
2415 they are in included files or evaltt'ed strings. The TRY block
2416 will then look for a CATCH block that will be processed. While
2417 it is being processed, the "error" variable will be set with the thrown
2418 exception as the value. After the TRY block - the FINAL
2419 block will be ran whether or not an error was thrown (unless a CATCH
2420 block throws an error).
2421
2422 Note: Parse errors cannot be caught unless they are in an eval FILTER, or are
2423 in a separate template being INCLUDEd or PROCESSed.
2424
2425 [% TRY %]
2426 Nothing bad happened.
2427 [% CATCH %]
2428 Caught the error.
2429 [% FINAL %]
2430 This section runs no matter what happens.
2431 [% END %]
2432
2433 Would print:
2434
2435 Nothing bad happened.
2436 This section runs no matter what happens.
2437
2438 Another example:
2439
2440 [% TRY %]
2441 [% THROW "Something happened" %]
2442 [% CATCH %]
2443 Error: [% error %]
2444 Error.type: [% error.type %]
2445 Error.info: [% error.info %]
2446 [% FINAL %]
2447 This section runs no matter what happens.
2448 [% END %]
2449
2450 Would print:
2451
2452 Error: undef error - Something happened
2453 Error.type: undef
2454 Error.info: Something happened
2455 This section runs no matter what happens.
2456
2457 You can give the error a type and more information including named arguments.
2458 This information replaces the "info" property of the exception.
2459
2460 [% TRY %]
2461 [% THROW foo.bar "Something happened" "grrrr" foo => 'bar' %]
2462 [% CATCH %]
2463 Error: [% error %]
2464 Error.type: [% error.type %]
2465 Error.info: [% error.info %]
2466 Error.info.0: [% error.info.0 %]
2467 Error.info.1: [% error.info.1 %]
2468 Error.info.args.0: [% error.info.args.0 %]
2469 Error.info.foo: [% error.info.foo %]
2470 [% END %]
2471
2472 Would print something like:
2473
2474 Error: foo.bar error - HASH(0x82a395c)
2475 Error.type: foo.bar
2476 Error.info: HASH(0x82a395c)
2477 Error.info.0: Something happened
2478 Error.info.1: grrrr
2479 Error.info.args.0: Something happened
2480 Error.info.foo: bar
2481
2482 You can also give the CATCH block a type to catch. And you
2483 can nest TRY blocks. If types are specified, CET will try and
2484 find the closest matching type. Also, an error object can
2485 be re-thrown using $error as the argument to THROW.
2486
2487 [% TRY %]
2488 [% TRY %]
2489 [% THROW foo.bar "Something happened" %]
2490 [% CATCH bar %]
2491 Caught bar.
2492 [% CATCH DEFAULT %]
2493 Caught default - but rethrew.
2494 [% THROW $error %]
2495 [% END %]
2496 [% CATCH foo %]
2497 Caught foo.
2498 [% CATCH foo.bar %]
2499 Caught foo.bar.
2500 [% CATCH %]
2501 Caught anything else.
2502 [% END %]
2503
2504 Would print:
2505
2506 Caught default - but rethrew.
2507
2508 Caught foo.bar.
2509
2510 =item C<UNLESS>
2511
2512 Same as IF but condition is negated.
2513
2514 [% UNLESS 0 %]hi[% END %] => hi
2515
2516 Can also be a post operative directive.
2517
2518 =item C<USE>
2519
2520 Allows for loading a Template::Toolkit style plugin.
2521
2522 [% USE iter = Iterator(['foo', 'bar']) %]
2523 [%~ iter.get_first %]
2524 [% iter.size %]
2525
2526 Would print:
2527
2528 foo
2529 2
2530
2531 Note that it is possible to send arguments to the new object
2532 constructor. It is also possible to omit the variable name being
2533 assigned. In that case the name of the plugin becomes the variable.
2534
2535 [% USE Iterator(['foo', 'bar', 'baz']) %]
2536 [%~ Iterator.get_first %]
2537 [% Iterator.size %]
2538
2539 Would print:
2540
2541 foo
2542 3
2543
2544 Plugins that are loaded are looked up for in the namespace listed in
2545 the PLUGIN_BASE directive which defaults to Template::Plugin. So in
2546 the previous example, if Template::Toolkit was installed, the iter
2547 object would loaded by the class Template::Plugin::Iterator. In CET,
2548 an effective way to disable plugins is to set the PLUGIN_BASE to a
2549 non-existent base such as "_" (In TT it will still fall back to look
2550 in Template::Plugin).
2551
2552 Note: The iterator plugin will fall back and use
2553 CGI::Ex::Template::Iterator if Template::Toolkit is not installed. No
2554 other plugins come installed with CGI::Ex::Template.
2555
2556 The names of the Plugin being loaded from PLUGIN_BASE are case
2557 insensitive. However, using case insensitive names is bad as it
2558 requires scanning the @INC directories for any module matching the
2559 PLUGIN_BASE and caching the result (OK - not that bad).
2560
2561 If the plugin is not found and the LOAD_PERL directive is set, then
2562 CET will try and load a module by that name (note: this type of lookup
2563 is case sensitive and will not scan the @INC dirs for a matching
2564 file).
2565
2566 # The LOAD_PERL directive should be set to 1
2567 [% USE cet = CGI::Ex::Template %]
2568 [%~ cet.dump_parse_expr('2 * 3').replace('\s+', ' ') %]
2569
2570 Would print:
2571
2572 $VAR1 = [ [ undef, '*', '2', '3' ], 0 ];
2573
2574 See the PLUGIN_BASE, and PLUGINS configuration items.
2575
2576 See the documentation for Template::Manual::Plugins.
2577
2578 =item C<VIEW>
2579
2580 Implement a TT style view. For more information, please
2581 see the Template::View documentation. This DIRECTIVE
2582 will correctly parse the arguments and then pass them
2583 along to a newly created Template::View object. It
2584 will fail if Template::View can not be found.
2585
2586 =item C<WHILE>
2587
2588 Will process a block of code while a condition is true.
2589
2590 [% WHILE i < 3 %]
2591 [%~ i = i + 1 %]
2592 i = [% i %]
2593 [%~ END %]
2594
2595 Would print:
2596
2597 i = 1
2598 i = 2
2599 i = 3
2600
2601 You could also do:
2602
2603 [% i = 4 %]
2604 [% WHILE (i = i - 1) %]
2605 i = [% i %]
2606 [%~ END %]
2607
2608 Would print:
2609
2610 i = 3
2611 i = 2
2612 i = 1
2613
2614 Note that (f = f - 1) is a valid expression that returns the value
2615 of the assignment. The parenthesis are not optional.
2616
2617 WHILE has a built in limit of 1000 iterations. This is controlled by the
2618 global variable $WHILE_MAX in CGI::Ex::Template.
2619
2620 WHILE may also be used as a post operative directive.
2621
2622 [% "$i" WHILE (i = i + 1) < 7 %] => 123456
2623
2624 =item C<WRAPPER>
2625
2626 Block directive. Processes contents of its block and then passes them
2627 in the [% content %] variable to the block or filename listed in the
2628 WRAPPER tag.
2629
2630 [% WRAPPER foo b = 23 %]
2631 My content to be processed ([% b %]).[% a = 2 %]
2632 [% END %]
2633
2634 [% BLOCK foo %]
2635 A header ([% a %]).
2636 [% content %]
2637 A footer ([% a %]).
2638 [% END %]
2639
2640 This would print.
2641
2642 A header (2).
2643 My content to be processed (23).
2644 A footer (2).
2645
2646 The WRAPPER directive may also be used as a post operative directive.
2647
2648 [% BLOCK baz %]([% content %])[% END -%]
2649 [% "foobar" WRAPPER baz %]
2650
2651 Would print
2652
2653 (foobar)');
2654
2655 Multiple filenames can be passed by separating them with a plus, a space,
2656 or commas (TT2 doesn't support the comma). Any supplied arguments will
2657 be used on all templates. Wrappers are processed in reverse order, so
2658 that the first wrapper listed will surround each subsequent wrapper listed.
2659 Variables from inner wrappers are available to the next wrapper that
2660 surrounds it.
2661
2662 [% WRAPPER "path/to/outer.html",
2663 "path/to/inner.html" a = "An arg" b = "Another arg" %]
2664
2665
2666 =back
2667
2668 =head1 DIRECTIVES (HTML::Template Style)
2669
2670 HTML::Template templates use directives that look similar to the
2671 following:
2672
2673 <TMPL_VAR NAME="foo">
2674
2675 <TMPL_IF NAME="bar">
2676 BAR
2677 </TMPL_IF>
2678
2679 The normal set of HTML::Template directives are TMPL_VAR,
2680 TMPL_IF, TMPL_ELSE, TMPL_UNLESS, TMPL_INCLUDE, and TMPL_LOOP.
2681 These tags should have either a NAME attribute, an EXPR attribute,
2682 or a bare variable name that is used to specify the value to
2683 be operated. If a NAME is specified, it may only be a single
2684 level value (as opposed to a TT chained variable). In the case
2685 of the TMPL_INCLUDE directive, the NAME is the file to be included.
2686
2687 In CET, the EXPR attribute can be used with any of these types to
2688 specify TT compatible variable or expression that will be used for
2689 the value.
2690
2691 <TMPL_VAR NAME="foo"> Prints the value contained in foo
2692 <TMPL_VAR foo> Prints the value contained in foo
2693 <TMPL_VAR EXPR="foo"> Prints the value contained in foo
2694
2695 <TMPL_VAR NAME="foo.bar.baz"> Prints the value contained in {'foo.bar.baz'}
2696 <TMPL_VAR EXPR="foo.bar.baz"> Prints the value contained in {foo}->{bar}->{baz}
2697
2698 <TMPL_IF foo> Prints FOO if foo is true
2699 FOO
2700 </TMPL_IF
2701
2702 <TMPL_UNLESS foo> Prints FOO unless foo is true
2703 FOO
2704 </TMPL_UNLESS
2705
2706 <TMPL_INCLUDE NAME="foo.ht"> Includes the template in "foo.ht"
2707
2708 <TMPL_LOOP foo> Iterates on the arrayref foo
2709 <TMPL_VAR name>
2710 </TMPL_LOOP>
2711
2712 CGI::Ex::Template makes all of the other TT3 directives available
2713 in addition to the normal set of HTML::Template directives. For
2714 example, the following is valid in CET.
2715
2716 <TMPL_MACRO bar(n) BLOCK>You said <TMPL_VAR n></TMPL_MACRO>
2717 <TMPL_GET bar("hello")>
2718
2719 The TMPL_VAR tag may also include an optional ESCAPE attribute.
2720 This specifies how the value of the tag should be escaped prior
2721 to substituting into the template.
2722
2723 Escape value | Type of escape
2724 ---------------------------------
2725 HTML, 1 | HTML encoding
2726 URL | URL encoding
2727 JS | basic javascript encoding (\n, \r, and \")
2728 NONE, 0 | No encoding (default).
2729
2730 The TMPL_VAR tag may also include an optional DEFAULT attribute
2731 that contains a string that will be used if the variable returns
2732 false.
2733
2734 <TMPL_VAR foo DEFAULT="Foo was false">
2735
2736 =head1 OPERATORS
2737
2738 The following operators are available in CGI::Ex::Template. Except
2739 where noted these are the same operators available in TT. They are
2740 listed in the order of their precedence (the higher the precedence the
2741 tighter it binds).
2742
2743 =over 4
2744
2745 =item C<.>
2746
2747 The dot operator. Allows for accessing sub-members, methods, or
2748 virtual methods of nested data structures.
2749
2750 my $obj->process(\$content, {a => {b => [0, {c => [34, 57]}]}}, \$output);
2751
2752 [% a.b.1.c.0 %] => 34
2753
2754 Note: on access to hashrefs, any hash keys that match the sub key name
2755 will be used before a virtual method of the same name. For example if
2756 a passed hash contained pair with a keyname "defined" and a value of
2757 "2", then any calls to hash.defined(another_keyname) would always
2758 return 2 rather than using the vmethod named "defined." To get around
2759 this limitation use the "|" operator (listed next). Also - on objects
2760 the "." will always try and call the method by that name. To always
2761 call the vmethod - use "|".
2762
2763 =item C<|>
2764
2765 The pipe operator. Similar to the dot operator. Allows for
2766 explicit calling of virtual methods and filters (filters are "merged"
2767 with virtual methods in CGI::Ex::Template and TT3) when accessing
2768 hashrefs and objects. See the note for the "." operator.
2769
2770 The pipe character is similar to TT2 in that it can be used in place
2771 of a directive as an alias for FILTER. It similar to TT3 in that it
2772 can be used for virtual method access. This duality is one source of
2773 difference between CGI::Ex::Template and TT2 compatibility. Templates
2774 that have directives that end with a variable name that then use the
2775 "|" directive to apply a filter will be broken as the "|" will be
2776 applied to the variable name.
2777
2778 The following two cases will do the same thing.
2779
2780 [% foo | html %]
2781
2782 [% foo FILTER html %]
2783
2784 Though they do the same thing, internally, foo|html is stored as a
2785 single variable while "foo FILTER html" is stored as the variable foo
2786 which is then passed to the FILTER html.
2787
2788 A TT2 sample that would break in CGI::Ex::Template or TT3 is:
2789
2790 [% PROCESS foo a = b | html %]
2791
2792 Under TT2 the content returned by "PROCESS foo a = b" would all be
2793 passed to the html filter. Under CGI::Ex::Template and TT3, b would
2794 be passed to the html filter before assigning it to the variable "a"
2795 before the template foo was processed.
2796
2797 A simple fix is to do any of the following:
2798
2799 [% PROCESS foo a = b FILTER html %]
2800
2801 [% | html %][% PROCESS foo a = b %][% END %]
2802
2803 [% FILTER html %][% PROCESS foo a = b %][% END %]
2804
2805 This shouldn't be too much hardship and offers the great return of disambiguating
2806 virtual method access.
2807
2808 =item C<\>
2809
2810 Unary. The reference operator. Not well publicized in TT. Stores a reference
2811 to a variable for use later. Can also be used to "alias" long names.
2812
2813 [% f = 7 ; foo = \f ; f = 8 ; foo %] => 8
2814
2815 [% foo = \f.g.h.i.j.k; f.g.h.i.j.k = 7; foo %] => 7
2816
2817 [% f = "abcd"; foo = \f.replace("ab", "-AB-") ; foo %] => -AB-cd
2818
2819 [% f = "abcd"; foo = \f.replace("bc") ; foo("-BC-") %] => a-BC-d
2820
2821 [% f = "abcd"; foo = \f.replace ; foo("cd", "-CD-") %] => ab-CD-
2822
2823 =item C<++ -->
2824
2825 Pre and post increment and decrement. My be used as either a prefix
2826 or postfix operator.
2827
2828 [% ++a %][% ++a %] => 12
2829
2830 [% a++ %][% a++ %] => 01
2831
2832 [% --a %][% --a %] => -1-2
2833
2834 [% a-- %][% a-- %] => 0-1
2835
2836 =item C<** ^ pow>
2837
2838 Right associative binary. X raised to the Y power. This isn't available in TT 2.15.
2839
2840 [% 2 ** 3 %] => 8
2841
2842 =item C<!>
2843
2844 Prefix not. Negation of the value.
2845
2846 =item C<->
2847
2848 Prefix minus. Returns the value multiplied by -1.
2849
2850 [% a = 1 ; b = -a ; b %] => -1
2851
2852 =item C<*>
2853
2854 Left associative binary. Multiplication.
2855
2856 =item C</ div DIV>
2857
2858 Left associative binary. Division. Note that / is floating point division, but div and
2859 DIV are integer division.
2860
2861 [% 10 / 4 %] => 2.5
2862 [% 10 div 4 %] => 2
2863
2864 =item C<% mod MOD>
2865
2866 Left associative binary. Modulus.
2867
2868 [% 15 % 8 %] => 7
2869
2870 =item C<+>
2871
2872 Left associative binary. Addition.
2873
2874 =item C<->
2875
2876 Left associative binary. Minus.
2877
2878 =item C<_ ~>
2879
2880 Left associative binary. String concatenation.
2881
2882 [% "a" ~ "b" %] => ab
2883
2884 =item C<< < > <= >= >>
2885
2886 Non associative binary. Numerical comparators.
2887
2888 =item C<lt gt le ge>
2889
2890 Non associative binary. String comparators.
2891
2892 =item C<eq>
2893
2894 Non associative binary. String equality test.
2895
2896 =item C<==>
2897
2898 Non associative binary. In TT syntaxes the V2EQUALS configuration
2899 item defaults to true which means this operator will operate
2900 the same as the "eq" operator. Setting V2EQUALS to 0 will
2901 change this operator to mean numeric equality. You could also use [% ! (a <=> b) %]
2902 but that is a bit messy.
2903
2904 The HTML::Template syntaxes default V2EQUALS to 0 which means
2905 that it will test for numeric equality just as you would normally
2906 expect.
2907
2908 In either case - you should always use "eq" when you mean "eq".
2909 The V2EQUALS will most likely eventually default to 0.
2910
2911 =item C<ne>
2912
2913 Non associative binary. String non-equality test.
2914
2915 =item C<!=>
2916
2917 Non associative binary. In TT syntaxes the V2EQUALS configuration
2918 item defaults to true which means this operator will operate
2919 the same as the "ne" operator. Setting V2EQUALS to 0 will
2920 change this operator to mean numeric non-equality.
2921 You could also use [% (a <=> b) %] but that is a bit messy.
2922
2923 The HTML::Template syntaxes default V2EQUALS to 0 which means
2924 that it will test for numeric non-equality just as you would
2925 normally expect.
2926
2927 In either case - you should always use "ne" when you mean "ne".
2928 The V2EQUALS will most likely eventually default to 0.
2929
2930 =item C<< <=> >>
2931
2932 Non associative binary. Numeric comparison operator. Returns -1 if the first argument is
2933 less than the second, 0 if they are equal, and 1 if the first argument is greater.
2934
2935 =item C<< cmp >>
2936
2937 Non associative binary. String comparison operator. Returns -1 if the first argument is
2938 less than the second, 0 if they are equal, and 1 if the first argument is greater.
2939
2940 =item C<&&>
2941
2942 Left associative binary. And. All values must be true. If all values are true, the last
2943 value is returned as the truth value.
2944
2945 [% 2 && 3 && 4 %] => 4
2946
2947 =item C<||>
2948
2949 Right associative binary. Or. The first true value is returned.
2950
2951 [% 0 || '' || 7 %] => 7
2952
2953 Note: perl is left associative on this operator - but it doesn't matter because
2954 || has its own precedence level. Setting it to right allows for CET to short
2955 circuit earlier in the expression optree (left is (((1,2), 3), 4) while right
2956 is (1, (2, (3, 4))).
2957
2958 =item C<..>
2959
2960 Non associative binary. Range creator. Returns an arrayref containing the values
2961 between and including the first and last arguments.
2962
2963 [% t = [1 .. 5] %] => variable t contains an array with 1,2,3,4, and 5
2964
2965 It is possible to place multiple ranges in the same [] constructor. This is not available in TT.
2966
2967 [% t = [1..3, 6..8] %] => variable t contains an array with 1,2,3,6,7,8
2968
2969 The .. operator is the only operator that returns a list of items.
2970
2971 =item C<? :>
2972
2973 Ternary - right associative. Can be nested with other ?: pairs.
2974
2975 [% 1 ? 2 : 3 %] => 2
2976 [% 0 ? 2 : 3 %] => 3
2977
2978 =item C<*= += -= /= **= %= ~=>
2979
2980 Self-modifying assignment - right associative. Sets the left hand side
2981 to the operation of the left hand side and right (clear as mud).
2982 In order to not conflict with SET, FOREACH and other operations, this
2983 operator is only available in parenthesis.
2984
2985 [% a = 2 %][% a += 3 %] --- [% a %] => --- 5 # is handled by SET
2986 [% a = 2 %][% (a += 3) %] --- [% a %] => 5 --- 5
2987
2988 =item C<=>
2989
2990 Assignment - right associative. Sets the left-hand side to the value of the righthand side. In order
2991 to not conflict with SET, FOREACH and other operations, this operator is only
2992 available in parenthesis. Returns the value of the righthand side.
2993
2994 [% a = 1 %] --- [% a %] => --- 1 # is handled by SET
2995 [% (a = 1) %] --- [% a %] => 1 --- 1
2996
2997 =item C<not NOT>
2998
2999 Prefix. Lower precedence version of the '!' operator.
3000
3001 =item C<and AND>
3002
3003 Left associative. Lower precedence version of the '&&' operator.
3004
3005 =item C<or OR>
3006
3007 Right associative. Lower precedence version of the '||' operator.
3008
3009 =item C<{}>
3010
3011 This operator is not used in TT. It is used internally
3012 by CGI::Ex::Template to delay the creation of a hash until the
3013 execution of the compiled template.
3014
3015 =item C<[]>
3016
3017 This operator is not used in TT. It is used internally
3018 by CGI::Ex::Template to delay the creation of an array until the
3019 execution of the compiled template.
3020
3021 =item C<qr>
3022
3023 This operator is not used in TT. It is used internally
3024 by CGI::Ex::Template to store a regular expression and its options.
3025 It will return a compiled Regexp object when compiled.
3026
3027 =back
3028
3029
3030 =head1 CHOMPING
3031
3032 Chomping refers to the handling of whitespace immediately before and
3033 immediately after template tags. By default, nothing happens to this
3034 whitespace. Modifiers can be placed just inside the opening and just
3035 before the closing tags to control this behavior.
3036
3037 Additionally, the PRE_CHOMP and POST_CHOMP configuration variables can
3038 be set and will globally control all chomping behavior for tags that
3039 do not have their own chomp modifier. PRE_CHOMP and POST_CHOMP can
3040 be set to any of the following values:
3041
3042 none: 0 + Template::Constants::CHOMP_NONE
3043 one: 1 - Template::Constants::CHOMP_ONE
3044 collapse: 2 = Template::Constants::CHOMP_COLLAPSE
3045 greedy: 3 ~ Template::Constants::CHOMP_GREEDY
3046
3047 =over 4
3048
3049 =item CHOMP_NONE
3050
3051 Don't do any chomping. The "+" sign is used to indicate CHOMP_NONE.
3052
3053 Hello.
3054
3055 [%+ "Hi." +%]
3056
3057 Howdy.
3058
3059 Would print:
3060
3061 Hello.
3062
3063 Hi.
3064
3065 Howdy.
3066
3067 =item CHOMP_ONE (formerly known as CHOMP_ALL)
3068
3069 Delete any whitespace up to the adjacent newline. The "-" is used to indicate CHOMP_ONE.
3070
3071 Hello.
3072
3073 [%- "Hi." -%]
3074
3075 Howdy.
3076
3077 Would print:
3078
3079 Hello.
3080 Hi.
3081 Howdy.
3082
3083 =item CHOMP_COLLAPSE
3084
3085 Collapse adjacent whitespace to a single space. The "=" is used to indicate CHOMP_COLLAPSE.
3086
3087 Hello.
3088
3089 [%= "Hi." =%]
3090
3091 Howdy.
3092
3093 Would print:
3094
3095 Hello. Hi. Howdy.
3096
3097 =item CHOMP_GREEDY
3098
3099 Remove all adjacent whitespace. The "~" is used to indicate CHOMP_GREEDY.
3100
3101 Hello.
3102
3103 [%~ "Hi." ~%]
3104
3105 Howdy.
3106
3107 Would print:
3108
3109 Hello.Hi.Howdy.
3110
3111 =head1 CONFIGURATION (TT STYLE)
3112
3113 The following TT2 configuration variables are supported (in
3114 alphabetical order). Note: for further discussion you can refer to
3115 the TT config documentation.
3116
3117 Items may be passed in upper or lower case.
3118
3119 These variables should be passed to the "new" constructor.
3120
3121 my $obj = CGI::Ex::Template->new(
3122 VARIABLES => \%hash_of_variables,
3123 AUTO_RESET => 0,
3124 TRIM => 1,
3125 POST_CHOMP => "=",
3126 PRE_CHOMP => "-",
3127 );
3128
3129
3130 =over 4
3131
3132 =item ABSOLUTE
3133
3134 Boolean. Default false. Are absolute paths allowed for included files.
3135
3136 =item ANYCASE
3137
3138 Allow directive matching to be case insensitive.
3139
3140 [% get 23 %] prints 23 with ANYCASE => 1
3141
3142 =item AUTO_RESET
3143
3144 Boolean. Default 1. Clear blocks that were set during the process method.
3145
3146 =item BLOCKS
3147
3148 A hashref of blocks that can be used by the process method.
3149
3150 BLOCKS => {
3151 block_1 => sub { ... }, # coderef that returns a block
3152 block_2 => 'A String', # simple string
3153 },
3154
3155 Note that a Template::Document cannot be supplied as a value (TT
3156 supports this). However, it is possible to supply a value that is
3157 equal to the hashref returned by the load_parsed_tree method.
3158
3159 =item CACHE_SIZE
3160
3161 Number of compiled templates to keep in memory. Default undef.
3162 Undefined means to allow all templates to cache. A value of 0 will
3163 force no caching. The cache mechanism will clear templates that have
3164 not been used recently.
3165
3166 =item COMPILE_DIR
3167
3168 Base directory to store compiled templates. Default undef. Compiled
3169 templates will only be stored if one of COMPILE_DIR and COMPILE_EXT is
3170 set.
3171
3172 =item COMPILE_EXT
3173
3174 Extension to add to stored compiled template filenames. Default undef.
3175
3176 =item CONSTANTS
3177
3178 Hashref. Used to define variables that will be "folded" into the
3179 compiled template. Variables defined here cannot be overridden.
3180
3181 CONSTANTS => {my_constant => 42},
3182
3183 A template containing:
3184
3185 [% constants.my_constant %]
3186
3187 Will have the value 42 compiled in.
3188
3189 Constants defined in this way can be chained as in [%
3190 constant.foo.bar.baz %].
3191
3192 =item CONSTANT_NAMESPACE
3193
3194 Allow for setting the top level of values passed in CONSTANTS. Default
3195 value is 'constants'.
3196
3197 =item DEBUG
3198
3199 Takes a list of constants |'ed together which enables different
3200 debugging modes. Alternately the lowercase names may be used
3201 (multiple values joined by a ",").
3202
3203 The only supported TT values are:
3204 DEBUG_UNDEF (2) - debug when an undefined value is used.
3205 DEBUG_DIRS (8) - debug when a directive is used.
3206 DEBUG_ALL (2047) - turn on all debugging.
3207
3208 Either of the following would turn on undef and directive debugging:
3209
3210 DEBUG => 'undef, dirs', # preferred
3211 DEBUG => 2 | 8,
3212 DEBUG => DEBUG_UNDEF | DEBUG_DIRS, # constants from Template::Constants
3213
3214 =item DEBUG_FORMAT
3215
3216 Change the format of messages inserted when DEBUG has DEBUG_DIRS set on.
3217 This essentially the same thing as setting the format using the DEBUG
3218 directive.
3219
3220 =item DEFAULT
3221
3222 The name of a default template file to use if the passed one is not found.
3223
3224 =item DELIMITER
3225
3226 String to use to split INCLUDE_PATH with. Default is :. It is more
3227 straight forward to just send INCLUDE_PATH an arrayref of paths.
3228
3229 =item DUMP
3230
3231 Configures the behavior of the DUMP tag. May be set to 0, a hashref,
3232 or another true value. Default is true.
3233
3234 If set to 0, all DUMP directives will do nothing. This is useful if
3235 you would like to turn off the DUMP directives under some environments.
3236
3237 IF set to a true value (or undefined) then DUMP directives will operate.
3238
3239 If set to a hashref, the values of the hash can be used to configure
3240 the operation of the DUMP directives. The following are the values
3241 that can be set in this hash.
3242
3243 =over 4
3244
3245 =item EntireStash
3246
3247 Default 1. If set to 0, then the DUMP directive will not print the
3248 entire contents of the stash when a DUMP directive is called without
3249 arguments.
3250
3251 =item handler
3252
3253 Defaults to an internal coderef. If set to a coderef, the DUMP directive will pass the
3254 arguments to be dumped and expects a string with the dumped data. This
3255 gives complete control over the dump process.
3256
3257 Note 1: The default handler makes sure that values matching the
3258 private variable regex are not included. If you install your own handler,
3259 you will need to take care of these variables if you intend for them
3260 to not be shown.
3261
3262 Note 2: If you would like the name of the variable to be dumped, include
3263 the string '$VAR1' and the DUMP directive will interpolate the value. For
3264 example, to dump all output as YAML - you could do the following:
3265
3266 DUMP => {
3267 handler => sub {
3268 require YAML;
3269 return "\$VAR1 =\n".YAML::Dump(shift);
3270 },
3271 }
3272
3273 =item header
3274
3275 Default 1. Controls whether a header is printed for each DUMP directive.
3276 The header contains the file and line number the DUMP directive was
3277 called from. If set to 0 the headers are disabled.
3278
3279 =item html
3280
3281 Defaults to 1 if $ENV{'REQUEST_METHOD'} is set - 0 otherwise. If set to
3282 1, then the output of the DUMP directive is passed to the html filter
3283 and encased in "pre" tags. If set to 0 no html encoding takes place.
3284
3285 =item Sortkeys, Useqq, Ident, Pad, etc
3286
3287 Any of the Data::Dumper configuration items may be passed.
3288
3289 =back
3290
3291 =item END_TAG
3292
3293 Set a string to use as the closing delimiter for TT. Default is "%]".
3294
3295 =item ERROR
3296
3297 Used as a fall back when the processing of a template fails. May either
3298 be a single filename that will be used in all cases, or may be a hashref
3299 of options where the keynames represent error types that will be handled
3300 by the filename in their value. A key named default will be used if no
3301 other matching keyname can be found. The selection process is similar
3302 to that of the TRY/CATCH/THROW directives (see those directives for more
3303 information).
3304
3305 my $t = CGI::Ex::Template->new({
3306 ERROR => 'general/catch_all_errors.html',
3307 });
3308
3309 my $t = CGI::Ex::Template->new({
3310 ERROR => {
3311 default => 'general/catch_all_errors.html',
3312 foo => 'catch_all_general_foo_errors.html',
3313 'foo.bar' => 'catch_foo_bar_errors.html',
3314 },
3315 });
3316
3317 Note that the ERROR handler will only be used for errors during the
3318 processing of the main document. It will not catch errors that
3319 occur in templates found in the PRE_PROCESS, POST_PROCESS, and WRAPPER
3320 configuration items.
3321
3322 =item ERRORS
3323
3324 Same as the ERROR configuration item. Both may be used interchangably.
3325
3326 =item EVAL_PERL
3327
3328 Boolean. Default false. If set to a true value, PERL and RAWPERL blocks
3329 will be allowed to run. This is a potential security hole, as arbitrary
3330 perl can be included in the template. If Template::Toolkit is installed,
3331 a true EVAL_PERL value also allows the perl and evalperl filters to be used.
3332
3333 =item FILTERS
3334
3335 Allow for passing in TT style filters.
3336
3337 my $filters = {
3338 filter1 => sub { my $str = shift; $s =~ s/./1/gs; $s },
3339 filter2 => [sub { my $str = shift; $s =~ s/./2/gs; $s }, 0],
3340 filter3 => [sub { my ($context, @args) = @_; return sub { my $s = shift; $s =~ s/./3/gs; $s } }, 1],
3341 };
3342
3343 my $str = q{
3344 [% a = "Hello" %]
3345 1 ([% a | filter1 %])
3346 2 ([% a | filter2 %])
3347 3 ([% a | filter3 %])
3348 };
3349
3350 my $obj = CGI::Ex::Template->new(FILTERS => $filters);
3351 $obj->process(\$str) || die $obj->error;
3352
3353 Would print:
3354
3355 1 (11111)
3356 2 (22222)
3357 3 (33333)
3358
3359 Filters passed in as an arrayref should contain a coderef and a value
3360 indicating if they are dynamic or static (true meaning dynamic). The
3361 dynamic filters are passed the pseudo context object and any arguments
3362 and should return a coderef that will be called as the filter. The filter
3363 coderef is then passed the string.
3364
3365 =item INCLUDE_PATH
3366
3367 A string or an arrayref or coderef that returns an arrayref that
3368 contains directories to look for files included by processed
3369 templates.
3370
3371 =item INCLUDE_PATHS
3372
3373 Non-TT item. Same as INCLUDE_PATH but only takes an arrayref. If not specified
3374 then INCLUDE_PATH is turned into an arrayref and stored in INCLUDE_PATHS.
3375 Overrides INCLUDE_PATH.
3376
3377 =item INTERPOLATE
3378
3379 Boolean. Specifies whether variables in text portions of the template will be
3380 interpolated. For example, the $variable and ${var.value} would be substituted
3381 with the appropriate values from the variable cache (if INTERPOLATE is on).
3382
3383 [% IF 1 %]The variable $variable had a value ${var.value}[% END %]
3384
3385 =item LOAD_PERL
3386
3387 Indicates if the USE directive can fall back and try and load a perl module
3388 if the indicated module was not found in the PLUGIN_BASE path. See the
3389 USE directive.
3390
3391 =item MAX_EVAL_RECURSE (CET only)
3392
3393 Will use $CGI::Ex::Template::MAX_EVAL_RECURSE if not present. Default is 50.
3394 Prevents runaway on the following:
3395
3396 [% f = "[% f|eval %]" %][% f|eval %]
3397
3398 =item MAX_MACRO_RECURSE (CET only)
3399
3400 Will use $CGI::Ex::Template::MAX_MACRO_RECURSE if not present. Default is 50.
3401 Prevents runaway on the following:
3402
3403 [% MACRO f BLOCK %][% f %][% END %][% f %]
3404
3405 =item NAMESPACE
3406
3407 No Template::Namespace::Constants support. Hashref of hashrefs representing
3408 constants that will be folded into the template at compile time.
3409
3410 CGI::Ex::Template->new(NAMESPACE => {constants => {
3411 foo => 'bar',
3412 }});
3413
3414 Is the same as
3415
3416 CGI::Ex::Template->new(CONSTANTS => {
3417 foo => 'bar',
3418 });
3419
3420 Any number of hashes can be added to the NAMESPACE hash.
3421
3422 =item NEGATIVE_STAT_TTL (Not in TT)
3423
3424 Defaults to STAT_TTL which defaults to $STAT_TTL which defaults to 1.
3425
3426 Similar to STAT_TTL - but represents the time-to-live
3427 seconds until a document that was not found is checked again against
3428 the system for modifications. Setting this number higher will allow for
3429 fewer file system accesses. Setting it to a negative number will allow
3430 for the file system to be checked every hit.
3431
3432 =item OUTPUT
3433
3434 Alternate way of passing in the output location for processed templates.
3435 If process is not passed an output argument, it will look for this value.
3436
3437 See the process method for a listing of possible values.
3438
3439 =item OUTPUT_PATH
3440
3441 Base path for files written out via the process method or via the redirect
3442 and file filters. See the redirect virtual method and the process method
3443 for more information.
3444
3445 =item PLUGINS
3446
3447 A hashref of mappings of plugin modules.
3448
3449 PLUGINS => {
3450 Iterator => 'Template::Plugin::Iterator',
3451 DBI => 'MyDBI',
3452 },
3453
3454 See the USE directive for more information.
3455
3456 =item PLUGIN_BASE
3457
3458 Default value is Template::Plugin. The base module namespace
3459 that template plugins will be looked for. See the USE directive
3460 for more information. May be either a single namespace, or an arrayref
3461 of namespaces.
3462
3463 =item POST_CHOMP
3464
3465 Set the type of chomping at the ending of a tag.
3466 See the section on chomping for more information.
3467
3468 =item POST_PROCESS
3469
3470 A list of templates to be processed and appended to the content
3471 after the main template. During this processing the "template"
3472 namespace will contain the name of the main file being processed.
3473
3474 This is useful for adding a global footer to all templates.
3475
3476 =item PRE_CHOMP
3477
3478 Set the type of chomping at the beginning of a tag.
3479 See the section on chomping for more information.
3480
3481 =item PRE_DEFINE
3482
3483 Same as the VARIABLES configuration item.
3484
3485 =item PRE_PROCESS
3486
3487 A list of templates to be processed before and pre-pended to the content
3488 before the main template. During this processing the "template"
3489 namespace will contain the name of the main file being processed.
3490
3491 This is useful for adding a global header to all templates.
3492
3493 =item PROCESS
3494
3495 Specify a file to use as the template rather than the one passed in
3496 to the ->process method.
3497
3498 =item RECURSION
3499
3500 Boolean. Default false. Indicates that INCLUDED or PROCESSED files
3501 can refer to each other in a circular manner. Be careful about recursion.
3502
3503 =item RELATIVE
3504
3505 Boolean. Default false. If true, allows filenames to be specified
3506 that are relative to the currently running process.
3507
3508 =item SEMICOLONS
3509
3510 Boolean. Default fast. If true, then the syntax will require that
3511 semi-colons separate multiple directives in the same tag. This is
3512 useful for keeping the syntax a little more clean as well as trouble
3513 shooting some errors.
3514
3515 =item START_TAG
3516
3517 Set a string to use as the opening delimiter for TT. Default is "[%".
3518
3519 =item STAT_TTL
3520
3521 Defaults to $STAT_TTL which defaults to 1. Represents time-to-live
3522 seconds until a cached in memory document is compared to the file
3523 system for modifications. Setting this number higher will allow for
3524 fewer file system accesses. Setting it to a negative number will allow
3525 for the file system to be checked every hit.
3526
3527 =item SYNTAX (not in TT)
3528
3529 Defaults to "cet". Indicates the syntax that will be used for parsing
3530 included templates or eval'ed strings. You can use the CONFIG
3531 directive to change the SYNTAX on the fly (it will not affect
3532 the syntax of the document currently being parsed).
3533
3534 The syntax may be passed in upper or lower case.
3535
3536 The available choices are:
3537
3538 cet - CGI::Ex::Template style - the same as TT3
3539 tt3 - Template::Toolkit ver3 - same as CET
3540 tt2 - Template::Toolkit ver2 - almost the same as TT3
3541 tt1 - Template::Toolkit ver1 - almost the same as TT2
3542 ht - HTML::Template - same as HTML::Template::Expr without EXPR
3543 hte - HTML::Template::Expr
3544
3545 Passing in a different syntax allows for the process method
3546 to use a non-TT syntax and for the output method to use a non-HT
3547 syntax.
3548
3549 The following is a sample of HTML::Template interface usage parsing
3550 a Template::Toolkit style document.
3551
3552 my $obj = CGI::Ex::Template->new(filename => 'my/template.tt'
3553 syntax => 'cet');
3554 $obj->param(\%swap);
3555 print $obj->output;
3556
3557 The following is a sample of Template::Toolkit interface usage parsing
3558 a HTML::Template::Expr style document.
3559
3560 my $obj = CGI::Ex::Template->new(SYNTAX => 'hte');
3561 $obj->process('my/template.ht', \%swap);
3562
3563 You can use the define_syntax method to add another custom syntax to
3564 the list of available options.
3565
3566 =item TAG_STYLE
3567
3568 Allow for setting the type of tag delimiters to use for parsing the TT.
3569 See the TAGS directive for a listing of the available types.
3570
3571 =item TRIM
3572
3573 Remove leading and trailing whitespace from blocks and templates.
3574 This operation is performed after all enclosed template tags have
3575 been executed.
3576
3577 =item UNDEFINED_ANY
3578
3579 This is not a TT configuration option. This option expects to be a code
3580 ref that will be called if a variable is undefined during a call to play_expr.
3581 It is passed the variable identity array as a single argument. This
3582 is most similar to the "undefined" method of Template::Stash. It allows
3583 for the "auto-defining" of a variable for use in the template. It is
3584 suggested that UNDEFINED_GET be used instead as UNDEFINED_ANY is a little
3585 to general in defining variables.
3586
3587 You can also sub class the module and override the undefined_any method.
3588
3589 =item UNDEFINED_GET
3590
3591 This is not a TT configuration option. This option expects to be a code
3592 ref that will be called if a variable is undefined during a call to GET.
3593 It is passed the variable identity array as a single argument. This is more useful
3594 than UNDEFINED_ANY in that it is only called during a GET directive
3595 rather than in embedded expressions (such as [% a || b || c %]).
3596
3597 You can also sub class the module and override the undefined_get method.
3598
3599 =item V1DOLLAR
3600
3601 This allows for some compatibility with TT1 templates. The only real
3602 behavior change is that [% $foo %] becomes the same as [% foo %]. The
3603 following is a basic table of changes invoked by using V1DOLLAR.
3604
3605 With V1DOLLAR Equivalent Without V1DOLLAR (Normal default)
3606 "[% foo %]" "[% foo %]"
3607 "[% $foo %]" "[% foo %]"
3608 "[% ${foo} %]" "[% ${foo} %]"
3609 "[% foo.$bar %]" "[% foo.bar %]"
3610 "[% ${foo.bar} %]" "[% ${foo.bar} %]"
3611 "[% ${foo.$bar} %]" "[% ${foo.bar} %]"
3612 "Text: $foo" "Text: $foo"
3613 "Text: ${foo}" "Text: ${foo}"
3614 "Text: ${$foo}" "Text: ${foo}"
3615
3616 =item V2EQUALS
3617
3618 Default 1 in TT syntaxes, defaults to 0 in HTML::Template syntaxes.
3619
3620 If set to 1 then "==" is an alias for "eq" and "!= is an alias for
3621 "ne".
3622
3623 [% CONFIG V2EQUALS => 1 %][% ('7' == '7.0') || 0 %]
3624 [% CONFIG V2EQUALS => 0 %][% ('7' == '7.0') || 0 %]
3625
3626 Prints
3627
3628 0
3629 1
3630
3631 =item V2PIPE
3632
3633 Restores the behavior of the pipe operator to be compatible with TT2.
3634
3635 With V2PIPE = 1
3636
3637 [%- BLOCK a %]b is [% b %]
3638 [% END %]
3639 [%- PROCESS a b => 237 | repeat(2) %]
3640
3641 # output of block "a" with b set to 237 is passed to the repeat(2) filter
3642
3643 b is 237
3644 b is 237
3645
3646 With V2PIPE = 0 (default)
3647
3648 [%- BLOCK a %]b is [% b %]
3649 [% END %]
3650 [% PROCESS a b => 237 | repeat(2) %]
3651
3652 # b set to 237 repeated twice, and b passed to block "a"
3653
3654 b is 237237
3655
3656 =item VARIABLES
3657
3658 A hashref of variables to initialize the template stash with. These
3659 variables are available for use in any of the executed templates.
3660 See the section on VARIABLES for the types of information that can be passed in.
3661
3662 =item VMETHOD_FUNCTIONS
3663
3664 Defaults to 1. All scalar virtual methods are available as top level functions as well.
3665 This is not true of TT2. In CGI::Ex::Template the following are equivalent:
3666
3667 [% "abc".length %]
3668 [% length("abc") %]
3669
3670 You may set VMETHOD_FUNCTIONS to 0 to disable this behavior.
3671
3672 =item WRAPPER
3673
3674 Operates similar to the WRAPPER directive. The option can be given a
3675 single filename, or an arrayref of filenames that will be used to wrap
3676 the processed content. If an arrayref is passed the filenames are
3677 processed in reverse order, so that the first filename specified will
3678 end up being on the outside (surrounding all other wrappers).
3679
3680 my $t = CGI::Ex::Template->new(
3681 WRAPPER => ['my/wrappers/outer.html', 'my/wrappers/inner.html'],
3682 );
3683
3684 Content generated by the PRE_PROCESS and POST_PROCESS will come before
3685 and after (respectively) the content generated by the WRAPPER
3686 configuration item.
3687
3688 See the WRAPPER direcive for more examples of how wrappers are construted.
3689
3690 =back
3691
3692 =head1 CONFIGURATION (HTML::Template STYLE)
3693
3694 The following HTML::Template and HTML::Template::Expr
3695 configuration variables are supported (in HTML::Template documentation order).
3696 Note: for further discussion you can refer to the HT documentation.
3697 Many of the variables mentioned in the TT CONFIGURATION section
3698 apply here as well. Unless noted, these items only apply when
3699 using the output method.
3700
3701 Items may be passed in upper or lower case.
3702
3703 These variables should be passed to the "new" constructor.
3704
3705 my $obj = CGI::Ex::Template->new(
3706 type => 'filename',
3707 source => 'my/template.ht',
3708 die_on_bad_params => 1,
3709 loop_context_vars => 1,
3710 global_vars => 1
3711 post_chomp => "=",
3712 pre_chomp => "-",
3713 );
3714
3715 =over 4
3716
3717 =item type
3718
3719 Can be one of filename, filehandle, arrayref, or scalarref. Indicates what type
3720 of input is in the "source" configuration item.
3721
3722 =item source
3723
3724 Stores where to read the input file. The type is specified in the "type"
3725 configuration item.
3726
3727 =item filename
3728
3729 Indicates a filename to read the template from. Same as putting the
3730 filename in the "source" item and setting "type" to "filename".
3731
3732 Must be set to enable caching.
3733
3734 =item filehandle
3735
3736 Should contain an open filehandle to read the template from. Same as
3737 putting the filehandle in the "source" item and setting "type" to "filehandle".
3738
3739 Will not be cached.
3740
3741 =item arrayref
3742
3743 Should contain an arrayref whose values are the lines of the template. Same as
3744 putting the arrayref in the "source" item and setting "type" to "arrayref".
3745
3746 Will not be cached.
3747
3748 =item scalarref
3749
3750 Should contain an reference to a scalar that contains the template. Same as
3751 putting the scalar ref in the "source" item and setting "type" to "scalarref".
3752
3753 Will not be cached.
3754
3755 =item cache
3756
3757 If set to one, then CET will use a global, in-memory document cache
3758 to store compiled templates in between calls. This is generally only
3759 useful in a mod_perl environment. The document is checked for a different
3760 modification time at each request.
3761
3762 =item blind_cache
3763
3764 Same as with cache enabled, but will not check if the document has
3765 been modified.
3766
3767 =item file_cache
3768
3769 If set to 1, will cache the compiled document on the file system. If
3770 true, file_cache_dir must be set.
3771
3772 =item file_cache_dir
3773
3774 The directory where to store cached documents when file_cache is true.
3775 This is similar to the TT compile_dir option.
3776
3777 =item double_file_cache
3778
3779 Uses a combination of file_cache and cache.
3780
3781 =item path
3782
3783 Same as INCLUDE_PATH when using the process method.
3784
3785 =item associate
3786
3787 May be a single CGI object or an arrayref of objects. The params
3788 from these objects will be added to the params during the
3789 output call.
3790
3791 =item case_sensitive
3792
3793 Allow passed variables set through the param method, or the
3794 associate configuration to be used case sensitively. Default is
3795 off. It is highly suggested that this be set to 1.
3796
3797 =item loop_context_vars
3798
3799 Default false. When true, calls to the loop directive will
3800 create the following variables that give information about the
3801 current iteration of the loop:
3802
3803 __first__ - True on first iteration only
3804 __last__ - True on last iteration only
3805 __inner__ - True on any iteration that isn't first or last
3806 __odd__ - True on odd iterations
3807 __counter__ - The iteration count
3808
3809 These variables are also available to LOOPs run under
3810 TT syntax if loop_context_vars is set and if QR_PRIVATE is set to 0.
3811
3812 =item no_includes
3813
3814 Default false. If true, calls to INCLUDE, PROCESS, WRAPPER and INSERT
3815 will fail. This option is also available when using the process method.
3816
3817 =item global_vars.
3818
3819 Default true in HTE mode. Default false in HT. Allows top level
3820 variables to be used in LOOPs. When false, only variables defined
3821 in the current LOOP iteration hashref will be available.
3822
3823 =item default_escape
3824
3825 Controls the type of escape used on named variables in TMPL_VAR
3826 directives. Can be one of HTML, URL, or JS. The values of
3827 TMPL_VAR directives will be encoded with this type unless
3828 they specify their own type via an ESCAPE attribute.
3829
3830 =back
3831
3832 =head1 UNSUPPORTED HT CONFIGURATION
3833
3834 =over 4
3835
3836 =item die_on_bad_params
3837
3838 CET does not resolve variables until the template is output.
3839
3840 =item force_untaint
3841
3842 =item strict
3843
3844 CET is strict on parsing HT documents.
3845
3846 =item shared_cache, double_cache
3847
3848 CET doesn't have shared caching. Yet.
3849
3850 =item search_path_on_include
3851
3852 CET will check the full path array on each include.
3853
3854 =item debug items
3855
3856 The HTML::Template style options are included here, but you
3857 can use the TT style DEBUG and DUMP directives to do intropection.
3858
3859 =item max_includes
3860
3861 CET uses TT's recursion protection.
3862
3863 =item filter
3864
3865 CET doesn't offer these.
3866
3867 =back
3868
3869 =head1 UNSUPPORTED TT2 CONFIGURATION
3870
3871 =over 4
3872
3873 =item LOAD_TEMPLATES
3874
3875 CGI::Ex::Template has its own mechanism for loading and storing
3876 compiled templates. TT would use a Template::Provider that would
3877 return a Template::Document. The closest thing in CGI::Ex::Template
3878 is the load_parsed_template method. There is no immediate plan to
3879 support the TT behavior.
3880
3881 =item LOAD_PLUGINS
3882
3883 CGI::Ex::Template uses its own mechanism for loading plugins. TT
3884 would use a Template::Plugins object to load plugins requested via the
3885 USE directive. The functionality for doing this in CGI::Ex::Template
3886 is contained in the list_plugins method and the play_USE method. There
3887 is no immediate plan to support the TT behavior.
3888
3889 Full support is offered for the PLUGINS and LOAD_PERL configuration items.
3890
3891 Also note that CGI::Ex::Template only natively supports the Iterator plugin.
3892 Any of the other plugins requested will need to provided by installing
3893 Template::Toolkit or the appropriate plugin module.
3894
3895 =item LOAD_FILTERS
3896
3897 CGI::Ex::Template uses its own mechanism for loading filters. TT
3898 would use the Template::Filters object to load filters requested via the
3899 FILTER directive. The functionality for doing this in CGI::Ex::Template
3900 is contained in the list_filters method and the play_expr method.
3901
3902 Full support is offered for the FILTERS configuration item.
3903
3904 =item TOLERANT
3905
3906 This option is used by the LOAD_TEMPLATES and LOAD_PLUGINS options and
3907 is not applicable in CGI::Ex::Template.
3908
3909 =item SERVICE
3910
3911 CGI::Ex::Template has no concept of service (theoretically the CGI::Ex::Template
3912 is the "service").
3913
3914 =item CONTEXT
3915
3916 CGI::Ex::Template provides its own pseudo context object to plugins,
3917 filters, and perl blocks. The CGI::Ex::Template model doesn't really
3918 allow for a separate context. CGI::Ex::Template IS the context.
3919
3920 =item STASH
3921
3922 CGI::Ex::Template manages its own stash of variables. A pseudo stash
3923 object is available via the pseudo context object for use in plugins,
3924 filters, and perl blocks.
3925
3926 =item PARSER
3927
3928 CGI::Ex::Template has its own built in parser. The closest similarity is
3929 the parse_tree method. The output of parse_tree is an optree that is
3930 later run by execute_tree. CET provides a backend to the Template::Parser::CET
3931 module which can be used to replace the default parser when using
3932 the standard Template::Toolkit library.
3933
3934 =item GRAMMAR
3935
3936 CGI::Ex::Template maintains its own grammar. The grammar is defined
3937 in the parse_tree method and the callbacks listed in the global
3938 $DIRECTIVES hashref.
3939
3940 =back
3941
3942
3943 =head1 VARIABLE PARSE TREE
3944
3945 CGI::Ex::Template parses templates into an tree of operations (an AST
3946 or abstract syntax tree). Even variable access is parsed into a tree.
3947 This is done in a manner somewhat similar to the way that TT operates
3948 except that nested variables such as foo.bar|baz contain the '.' or
3949 '|' in between each name level. Operators are parsed and stored as
3950 part of the variable (it may be more appropriate to say we are parsing
3951 a term or an expression).
3952
3953 The following table shows a variable or expression and the corresponding parsed tree
3954 (this is what the parse_expr method would return).
3955
3956 one [ 'one', 0 ]
3957 one() [ 'one', [] ]
3958 one.two [ 'one', 0, '.', 'two', 0 ]
3959 one|two [ 'one', 0, '|', 'two', 0 ]
3960 one.$two [ 'one', 0, '.', ['two', 0 ], 0 ]
3961 one(two) [ 'one', [ ['two', 0] ] ]
3962 one.${two().three} [ 'one', 0, '.', ['two', [], '.', 'three', 0], 0]
3963 2.34 2.34
3964 "one" "one"
3965 1 + 2 [ [ undef, '+', 1, 2 ], 0]
3966 a + b [ [ undef, '+', ['a', 0], ['b', 0] ], 0 ]
3967 "one"|length [ [ undef, '~', "one" ], 0, '|', 'length', 0 ]
3968 "one $a two" [ [ undef, '~', 'one ', ['a', 0], ' two' ], 0 ]
3969 [0, 1, 2] [ [ undef, '[]', 0, 1, 2 ], 0 ]
3970 [0, 1, 2].size [ [ undef, '[]', 0, 1, 2 ], 0, '.', 'size', 0 ]
3971 ['a', a, $a ] [ [ undef, '[]', 'a', ['a', 0], [['a', 0], 0] ], 0]
3972 {a => 'b'} [ [ undef, '{}', 'a', 'b' ], 0 ]
3973 {a => 'b'}.size [ [ undef, '{}', 'a', 'b' ], 0, '.', 'size', 0 ]
3974 {$a => b} [ [ undef, '{}', ['a', 0], ['b', 0] ], 0 ]
3975 a * (b + c) [ [ undef, '*', ['a', 0], [ [undef, '+', ['b', 0], ['c', 0]], 0 ]], 0 ]
3976 (a + b) [ [ undef, '+', ['a', 0], ['b', 0] ]], 0 ]
3977 (a + b) * c [ [ undef, '*', [ [undef, '+', ['a', 0], ['b', 0] ], 0 ], ['c', 0] ], 0 ]
3978 a ? b : c [ [ undef, '?', ['a', 0], ['b', 0], ['c', 0] ], 0 ]
3979 a || b || c [ [ undef, '||', ['a', 0], [ [undef, '||', ['b', 0], ['c', 0] ], 0 ] ], 0 ]
3980 ! a [ [ undef, '!', ['a', 0] ], 0 ]
3981
3982 Some notes on the parsing.
3983
3984 Operators are parsed as part of the variable and become part of the variable tree.
3985
3986 Operators are stored in the variable tree using an operator identity array which
3987 contains undef as the first value, the operator, and the operator arguments. This
3988 allows for quickly descending the parsed variable tree and determining that the next
3989 node is an operator.
3990
3991 Parenthesis () can be used at any point in an expression to disambiguate precedence.
3992
3993 "Variables" that appear to be literal strings or literal numbers
3994 are returned as the literal (no operator tree).
3995
3996 The following perl can be typed at the command line to view the parsed variable tree:
3997
3998 perl -e 'use CGI::Ex::Template; print CGI::Ex::Template::dump_parse_expr("foo.bar + 2")."\n"'
3999
4000 Also the following can be included in a template to view the output in a template:
4001
4002 [% USE cet = CGI::Ex::Template %]
4003 [%~ cet.dump_parse_expr('foo.bar + 2').replace('\s+', ' ') %]
4004
4005
4006 =head1 SEMI PUBLIC METHODS
4007
4008 The following list of methods are other interesting methods of CET that
4009 may be re-implemented by subclasses of CET.
4010
4011 =over 4
4012
4013 =item C<dump_parse>
4014
4015 This method allows for returning a Data::Dumper dump of a parsed
4016 template. It is mainly used for testing.
4017
4018 =item C<dump_parse_expr>
4019
4020 This method allows for returning a Data::Dumper dump of a parsed
4021 variable. It is mainly used for testing.
4022
4023 =item C<exception>
4024
4025 Creates an exception object blessed into the package listed in
4026 $CGI::Ex::Template::PACKAGE_EXCEPTION.
4027
4028 =item C<execute_tree>
4029
4030 Executes a parsed tree (returned from parse_tree)
4031
4032 =item C<play_expr>
4033
4034 Play the parsed expression. Turns a variable identity array into the
4035 parsed variable. This method is also responsible for playing
4036 operators and running virtual methods and filters. The variable
4037 identity array may also contain literal values, or operator identity
4038 arrays.
4039
4040 =item C<include_filename>
4041
4042 Takes a file path, and resolves it into the full filename using
4043 paths from INCLUDE_PATH or INCLUDE_PATHS.
4044
4045 =item C<_insert>
4046
4047 Resolves the file passed, and then returns its contents.
4048
4049 =item C<list_filters>
4050
4051 Dynamically loads the filters list from Template::Filters when a filter
4052 is used that is not natively implemented in CET.
4053
4054 =item C<list_plugins>
4055
4056 Returns an arrayref of modules that are under a base Namespace.
4057
4058 my @modules = @{ $self->list_plugins({base => 'Template::Plugins'}) }:
4059
4060 =item C<load_parsed_tree>
4061
4062 Given a filename or a string reference will return a parsed document
4063 hash that contains the parsed tree.
4064
4065 my $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");
4066
4067 =item C<parse_args>
4068
4069 Allow for the multitudinous ways that TT parses arguments. This allows
4070 for positional as well as named arguments. Named arguments can be separated with a "=" or "=>",
4071 and positional arguments should be separated by " " or ",". This only returns an array
4072 of parsed variables. To get the actual values, you must call play_expr on each value.
4073
4074 =item C<parse_tree>
4075
4076 Used by load_parsed_tree. This is the main grammar engine of the program. It
4077 uses method in the $DIRECTIVES hashref to parse different DIRECTIVE TYPES.
4078
4079 =item C<parse_expr>
4080
4081 Used to parse a variable, an expression, a literal string, or a number. It
4082 returns a parsed variable tree. Samples of parsed variables can be found in the VARIABLE PARSE TREE
4083 section.
4084
4085 =item C<set_variable>
4086
4087 Used to set a variable. Expects a variable identity array and the value to set. It
4088 will autovifiy as necessary.
4089
4090 =item C<throw>
4091
4092 Creates an exception object from the arguments and dies.
4093
4094 =item C<undefined_any>
4095
4096 Called during play_expr if a value is returned that is undefined. This could
4097 be used to magically create variables on the fly. This is similar to Template::Stash::undefined.
4098 It is suggested that undefined_get be used instead. Default behavior returns undef. You
4099 may also pass a coderef via the UNDEFINED_ANY configuration variable. Also, you can try using
4100 the DEBUG => 'undef', configuration option which will throw an error on undefined variables.
4101
4102 =item C<undefined_get>
4103
4104 Called when a variable is undefined during a GET directive. This is useful to
4105 see if a value that is about to get inserted into the text is undefined. undefined_any is a little
4106 too general for most cases. Also, you may pass a coderef via the UNDEFINED_GET configuration variable.
4107
4108 =back
4109
4110
4111 =head1 OTHER UTILITY METHODS
4112
4113 The following is a brief list of other methods used by CET. Generally, these
4114 shouldn't be overwritten by subclasses.
4115
4116 =over 4
4117
4118 =item C<apply_precedence>
4119
4120 Allows for parsed operator array to be translated to a tree based
4121 upon operator precedence.
4122
4123 =item C<context>
4124
4125 Used to create a "pseudo" context object that allows for portability
4126 of TT plugins, filters, and perl blocks that need a context object.
4127
4128 =item C<debug_node>
4129
4130 Used to get debug info on a directive if DEBUG_DIRS is set.
4131
4132 =item C<filter_*>
4133
4134 Methods by these names implement filters that are more complex than one liners.
4135
4136 =item C<get_line_number_by_index>
4137
4138 Used to turn string index position into line number
4139
4140 =item C<interpolate_node>
4141
4142 Used for parsing text nodes for dollar variables when interpolate is on.
4143
4144 =item C<parse_*>
4145
4146 Methods by these names are used by parse_tree to parse the template. These are the grammar.
4147
4148 =item C<play_*>
4149
4150 Methods by these names are used by execute_tree to execute the parsed tree.
4151
4152 =item C<play_operator>
4153
4154 Used to execute any found operators. The single argument is
4155 an operator identy returned by the parse_expr method (if the expression
4156 contained an operator). Normally you would just call play_expr
4157 instead and it will call play_operator if the structure
4158 contains an operator.
4159
4160 =item C<_process>
4161
4162 Called by process and the PROCESS, INCLUDE and other directives.
4163
4164 =item C<slurp>
4165
4166 Reads contents of passed filename - throws file exception on error.
4167
4168 =item C<split_paths>
4169
4170 Used to split INCLUDE_PATH or other directives if an arrayref is not passed.
4171
4172 =item C<_vars>
4173
4174 Return a reference to the current stash of variables. This is currently only used
4175 by the pseudo context object and may disappear at some point.
4176
4177 =item C<vmethod_*>
4178
4179 Methods by these names implement virtual methods that are more complex than oneliners.
4180
4181 =back
4182
4183
4184 =head1 AUTHOR
4185
4186 Paul Seamons <paul at seamons dot com>
4187
4188 =head1 LICENSE
4189
4190 This module may be distributed under the same terms as Perl itself.
4191
4192 =cut
This page took 0.214924 seconds and 4 git commands to generate.