3 CGI::Ex::Template - Fast and lightweight TT2/3 template engine
7 ### Template::Toolkit style usage
9 my $t = CGI::Ex::Template->new(
10 INCLUDE_PATH => ['/path/to/templates'],
21 $t->process('my/template.tt', $swap)
24 # process into a variable
26 $t->process('my/template.tt', $swap, \$out);
28 ### CET uses the same syntax and configuration as Template::Toolkit
31 ### HTML::Template style usage
33 my $t = CGI::Ex::Template->new(
34 filename => 'my/template.ht',
35 path => ['/path/to/templates'],
47 # print to STDOUT (errors die)
48 $t->output(print_to => \*STDOUT);
50 # process into a variable
53 ### CET can also use the same syntax and configuration as HTML::Template
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.
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.
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.
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).
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.
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.
102 So should you use CGI::Ex::Template ? Well, try it out. It may
103 give you no visible improvement. Or it could.
105 =head1 PUBLIC METHODS
107 The following section lists most of the publicly available methods. Some less
108 commonly used public methods are listed later in this document.
114 my $obj = CGI::Ex::Template->new({
115 INCLUDE_PATH => ['/my/path/to/content', '/my/path/to/content2'],
118 Arguments may be passed as a hash or as a hashref. Returns a CGI::Ex::Template object.
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.
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.
130 my $t = CGI::Ex::Template->new;
131 $t->process($in, $swap, $out)
134 Process takes three arguments.
136 The $in argument can be any one of:
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.
142 A reference to a scalar containing the contents of the template to be processed.
144 A coderef that will be called to return the contents of the template.
146 An open filehandle that will return the contents of the template when read.
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.
153 The $out argument can be any one of:
155 undef - meaning to print the completed template to STDOUT.
157 String containing a filename. The completed template will be placed in the file.
159 A reference to a string. The contents will be appended to the scalar reference.
161 A coderef. The coderef will be called with the contents as a single argument.
163 An object that can run the method "print". The contents will be passed as
164 a single argument to print.
166 An arrayref. The contents will be pushed onto the array.
168 An open filehandle. The contents will be printed to the open handle.
170 Additionally - the $out argument can be configured using the OUTPUT configuration
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.
177 my $obj = CGI::Ex::Template->new(SYNTAX => 'hte');
179 =item C<process_simple>
181 Similar to the process method but with the following restrictions:
183 The $in parameter is limited to a filename or a reference a string containing the contents.
185 The $out parameter may only be a reference to a scalar string that output will be appended to.
187 Additionally, the following configuration variables will be ignored: VARIABLES,
188 PRE_DEFINE, BLOCKS, PRE_PROCESS, PROCESS, POST_PROCESS, AUTO_RESET, OUTPUT.
192 Should something go wrong during a "process" command, the error that occurred can
193 be retrieved via the error method.
195 $obj->process('somefile.html', {a => 'b'}, \$string_ref)
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.
205 my $obj = CGI::Ex::Template->new(filename => 'myfile.html');
209 See the HTML::Template documentation for more information.
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.
215 my $obj = CGI::Ex::Template->new(SYNTAX => 'tt3');
217 Any errors that occur during the output method will die with the error as the die value.
221 HTML::Template way to get or set variable values that will be used by the output method.
223 my $val = $obj->param('key'); # get one value
225 $obj->param(key => $val); # set one value
227 $obj->param(key => $val, key2 => $val2); # set multiple
229 $obj->param({key => $val, key2 => $val2}); # set multiple
231 See the HTML::Template documentation for more information.
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.
236 =item C<define_vmethod>
238 This method is available for defining extra Virtual methods or filters. This method is similar
239 to Template::Stash::define_vmethod.
241 CGI::Ex::Template->define_vmethod(
243 reverse => sub { my $item = shift; return scalar reverse $item },
246 =item C<register_function>
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.
251 CGI::Ex::Template->register_function(
252 reverse => sub { my $item = shift; return scalar reverse $item },
255 =item C<define_directive>
257 This method can be used for adding new directives or overridding existing
260 CGI::Ex::Template->define_directive(
262 parse_sub => sub {}, # parse additional items in the tag
264 my ($self, $ref, $node, $out_ref) = @_;
265 $$out_ref .= "I always say the same thing!";
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
275 Now with a template like:
277 my $str = "([% MYDIR %]This is something[% END %])";
278 CGI::Ex::Template->new->process(\$str);
282 (I always say the same thing!)
284 We'll add more details in later revisions of this document.
286 =item C<define_syntax>
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.
292 CGI::Ex::Template->define_syntax(
293 my_uber_syntax => sub {
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(@_);
304 The subroutine that is used must return an opcode tree (AST) that
305 can be played by the execute_tree method.
307 =item C<define_operator>
309 This method allows for adding new operators or overriding existing ones.
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
316 my ($one, $two) = @_;
317 return "You've been foo'ed ($one, $two)";
321 You can then use it in a template as in the following:
323 my $str = "[% 'ralph' foo 1 + 2 * 3 %]";
324 CGI::Ex::Template->new->process(\$str);
328 You've been foo'ed (ralph, 7)
330 Future revisions of this document will include more samples.
336 Move module to its own namespace.
338 Cleanup operator API to allow for easier full customization of
341 Give better examples of overriding directives, syntax, and operators.
343 Add more functions to the XS version.
345 Find other syntaxes to include.
347 =head1 HOW IS CGI::Ex::Template DIFFERENT from Template::Toolkit
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
361 Numerical hash keys work
367 Quoted hash key interpolation is fine
369 [% a = {"$foo" => 1} %]
373 Multiple ranges in same constructor
375 [% a = [1..10, 21..30] %]
379 Constructor types can call virtual methods. (TT3)
381 [% a = [1..10].reverse %]
385 [% 123.length %] # = 3
387 [% 123.4.length %] # = 5
389 [% -123.4.length %] # = -5 ("." binds more tightly than "-")
393 [% "hi".repeat(3) %] # = hihihi
395 [% {a => b}.size %] # = 1
399 The "${" and "}" variable interpolators can contain expressions,
402 [% [0..10].${ 1 + 2 } %] # = 4
404 [% {ab => 'AB'}.${ 'a' ~ 'b' } %] # = AB
406 [% color = qw/Red Blue/; FOR [1..4] ; color.${ loop.index % color.size } ; END %]
411 You can use regular expression quoting.
413 [% "foo".match( /(F\w+)/i ).0 %] # = foo
419 [% f = "[% (1 + 2) %]" %][% f|eval %] # = 3
423 Arrays can be accessed with non-integer numbers.
425 [% [0..10].${ 2.3 } %] # = 3
429 Reserved names are less reserved. (TT3)
431 [% GET GET %] # gets the variable named "GET"
433 [% GET $GET %] # gets the variable who's name is stored in "GET"
437 Filters and SCALAR_OPS are interchangeable. (TT3)
445 Pipe "|" can be used anywhere dot "." can be and means to call
446 the virtual method. (TT3)
448 [% a = {size => "foo"} %][% a.size %] # = foo
450 [% a = {size => "foo"} %][% a|size %] # = 1 (size of hash)
454 Pipe "|" and "." can be mixed. (TT3)
456 [% "aa" | repeat(2) . length %] # = 4
460 Added V2PIPE configuration item
462 Restores the behavior of the pipe operator to be
467 [% PROCESS a | repeat(2) %] # = value of block or file a repeated twice
469 With V2PIPE = 0 (default)
471 [% PROCESS a | repeat(2) %] # = process block or file named a ~ a
475 Added V2EQUALS configuration item
477 Allows for turning off TT2 "==" behavior. Defaults to 1
478 in TT syntaxes and to 0 in HT syntaxes.
480 [% CONFIG V2EQUALS => 1 %][% ('7' == '7.0') || 0 %]
481 [% CONFIG V2EQUALS => 0 %][% ('7' == '7.0') || 0 %]
490 Added Virtual Object Namespaces. (TT3)
492 The Text, List, and Hash types give direct access
495 [% a = "foobar" %][% Text.length(a) %] # = 6
497 [% a = [1 .. 10] %][% List.size(a) %] # = 10
499 [% a = {a=>"A", b=>"B"} ; Hash.size(a) %] = 2
501 [% foo = {a => 1, b => 2}
503 | List.join(", ") %] # = a, b
507 Added "fmt" scalar, list, and hash virtual methods.
509 [% list.fmt("%s", ", ") %]
511 [% hash.fmt("%s => %s", "\n") %]
515 Added missing HTML::Template::Expr vmethods
517 The following vmethods were added - they correspond to the
518 perl functions of the same name.
536 Allow all Scalar vmethods to behave as top level functions.
538 [% sprintf("%d %d", 7, 8) %] # = "7 8"
540 The following are equivalent in CET:
545 This feature may be disabling by setting the
546 VMETHOD_FUNCTIONS configuration item to 0.
548 This is similar to how HTML::Template::Expr operates, but
549 now you can use this functionality in TT templates as well.
553 Whitespace is less meaningful. (TT3)
555 [% 2-1 %] # = 1 (fails in TT2)
561 [% 2 ** 3 %] [% 2 pow 3 %] # = 8 8
565 Added string comparison operators (gt ge lt le cmp)
567 [% IF "a" lt "b" %]a is less[% END %]
571 Added numeric comparison operator (<=>)
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).
576 [% IF ! (a <=> b) %]a == b[% END %]
578 [% IF (a <=> b) %]a != b[% END %]
582 Added self modifiers (+=, -=, *=, /=, %=, **=, ~=). (TT3)
584 [% a = 2; a *= 3 ; a %] # = 6
585 [% a = 2; (a *= 3) ; a %] # = 66
589 Added pre and post increment and decrement (++ --). (TT3)
591 [% ++a ; ++a %] # = 12
592 [% a-- ; a-- %] # = 0-1
596 Added qw// contructor. (TT3)
598 [% a = qw(a b c); a.1 %] # = b
600 [% qw/a b c/.2 %] # = c
604 Added regex contructor. (TT3)
606 [% "FOO".match(/(foo)/i).0 %] # = FOO
608 [% a = /(foo)/i; "FOO".match(a).0 %] # = FOO
612 Allow for scientific notation. (TT3)
616 [% 123.fmt('%.3e') %] # = 1.230e+02
620 Allow for hexidecimal input. (TT3)
622 [% a = 0xff0000 %][% a %] # = 16711680
624 [% a = 0xff2 / 0xd; a.fmt('%x') %] # = 13a
628 FOREACH variables can be nested.
630 [% FOREACH f.b = [1..10] ; f.b ; END %]
632 Note that nested variables are subject to scoping issues.
633 f.b will not be reset to its value before the FOREACH.
637 Post operative directives can be nested. (TT3)
639 Andy Wardley calls this side-by-side effect notation.
641 [% one IF two IF three %]
645 [% IF three %][% IF two %][% one %][% END %][% END %]
648 [% a = [[1..3], [5..7]] %][% i FOREACH i = j FOREACH j = a %] # = 123567
652 Semi-colons on directives in the same tag are optional. (TT3)
658 [% FOREACH i = [1 .. 10]
662 Note: a semi-colon is still required in front of any block directive
663 that can be used as a post-operative directive.
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.
679 CATCH blocks can be empty.
681 TT2 requires them to contain something.
685 Added a DUMP directive.
687 Used for Data::Dumpering the passed variable or expression.
693 Added CONFIG directive.
702 Configuration options can use lowercase names instead
703 of the all uppercase names that TT2 uses.
705 my $t = CGI::Ex::Template->new({
712 Added LOOP directive (works the same as LOOP in HTML::Template.
714 [%- var = [{key => 'a'}, {key => 'b'}] %]
726 CET can parse HTML::Template and HTML::Template::Expr documents
727 as well as TT2 and TT3 documents.
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.
735 [% CONFIG SYNTAX => 'hte' %]
736 [% var = '<TMPL_VAR EXPR="sprintf('%s', 'hello world')">' %]
741 CET does not generate Perl code.
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
750 CET uses storable for its compiled templates.
752 If EVAL_PERL is off, CET will not eval_string on ANY piece of information.
756 There is eval_filter and MACRO recursion protection
758 You can control the nested nature of eval_filter and MACRO
759 recursion using the MAX_EVAL_RECURSE and MAX_MACRO_RECURSE
766 CET provides a context object that mimics the Template::Context
767 interface for use by some TT filters, eval perl blocks, views,
774 Well there is but it isn't an object.
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.
783 There is no provider.
785 CET uses the load_parsed_tree method to get and cache templates.
789 There is no parser/grammar.
791 CET has its own built-in recursive regex based parser and grammar system.
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
800 The DEBUG directive is more limited.
802 It only understands DEBUG_DIRS (8) and DEBUG_UNDEF (2).
806 CET has better line information
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.
811 Parse errors actually know what line and character they occured at.
815 =head1 HOW IS CGI::Ex::Template DIFFERENT from HTML::Template
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.
823 The TMPL_VAR, TMPL_IF, TMPL_ELSE, TMPL_UNLESS, TMPL_LOOP, and TMPL_INCLUDE
824 all work identically to HTML::Template.
830 Added support for other TT3 directives and for TT style "dot notation."
833 <TMPL_SET b = [1 .. 25]>
834 <TMPL_SET foo = PROCESS 'filename.tt'>
836 <TMPL_GET foo> # similar to <TMPL_VAR NAME="foo">
838 <TMPL_GET my.nested.chained.variable.1>
839 <TMPL_GET my_var | html>
841 <TMPL_USE foo = DBI(db => ...)>
842 <TMPL_CALL foo.connect>
844 Any of the TT directives can be used in HTML::Template documents.
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.
866 Added CHOMP capabilities (PRE_CHOMP and POST_CHOMP)
869 <~TMPL_VAR EXPR="1+2"~>
876 Added INTERPOLATE capability
878 <TMPL_SET foo = 'FOO'>
879 <TMPL_CONFIG INTERPOLATE => 1>
880 $foo <TMPL_GET foo> ${ 1 + 2 }
888 Allow for HTML::Template templates to include TT style templates.
890 <TMPL_CONFIG SYNTAX => 'tt3'>
891 <TMPL_INCLUDE "filename.tt">
895 Allow for Expr parsing to follow proper precedence rules.
897 <TMPL_VAR EXPR="1 + 2 * 3">
903 Uses all of the caching and opcode tree optimations provided by
904 CGI::Ex::Template and CGI::Ex::Template::XS.
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.
917 This section discusses how to use variables and expressions in the TT
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.
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.
932 The following are some sample ways to access variables.
934 ### some sample variables
939 some_code => sub { "You passed me (".join(', ', @_).")" },
943 c => [3, 1, 4, 1, 5, 9],
946 my_list => [20 .. 50],
947 cet => CGI::Ex::Template->new,
950 ### pass the variables into the CET process
951 $cet->process($template_name, \%vars)
954 ### pass the variables during object creation (will be available to every process call)
955 my $cet = CGI::Ex::Template->new(VARIABLES => \%vars);
957 =head2 GETTING VARIABLES
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
967 Would print when processed:
973 To access members of a hashref or an arrayref, you can chain together
974 the names using a ".".
977 [% my_list.0] [% my_list.1 %] [% my_list.-1 %]
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.
993 [% some_code(one, 2, 3) %]
1000 You passed me (1.0, 2, 3).
1002 If the value of a variable is an object, methods can be called using
1007 [% cet.dump_parse_expr('1 + 2').replace('\s+', ' ') %]
1009 Would print something like:
1011 CGI::Ex::Template=HASH(0x814dc28)
1013 $VAR1 = [ [ undef, '+', '1', '2' ], 0 ];
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
1023 [% some_data.c.join(" | ") %]
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
1038 [% ${some_data.vname} %]
1039 [% some_data.$foo %]
1040 [% some_data.${foo} %]
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)
1054 [% ['a'..'z'].${ 2.3 } %]
1055 [% {ab => 'AB'}.${ 'a' ~ 'b' } %]
1056 [% color = qw/Red Blue/; FOR [1..4] ; color.${ loop.index % color.size } ; END %]
1064 =head2 SETTING VARIABLES.
1066 To define variables during processing, you can use the = operator. In
1067 most cases this is the same as using the SET directive.
1069 [% a = 234 %][% a %]
1070 [% SET b = "Hello" %][% b %]
1077 It is also possible to create arrayrefs and hashrefs.
1080 [% b = {key1 => 'val1', 'key2' => 'val2'} %]
1083 [% b.key1 %] [% b.key2 %]
1090 It is possible to set multiple values in the same SET directive.
1095 [% a %] [% b %] [% c %]
1101 It is also possible to unset variables, or to set members of
1102 nested data structures.
1117 =head1 LITERALS AND CONSTRUCTORS
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.
1127 =item Integers and Numbers.
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)
1134 Scientific notation is supported.
1136 [% 314159e-5 + 0 %] Prints 3.14159.
1138 [% .0000001.fmt('%.1e') %] Prints 1.0e-07
1140 Hexidecimal input is also supported.
1142 [% 0xff + 0 %] Prints 255
1144 [% 48875.fmt('%x') %] Prints beeb
1146 =item Single quoted strings.
1148 Returns the string. No variable interpolation happens.
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.
1156 Note: virtual methods can only be used on literal strings in CET, not in TT.
1158 You may also embed the current tags in strings (CET only).
1160 [% '[% 1 + 2 %]' | eval %] Prints "3"
1162 =item Double quoted strings.
1164 Returns the string. Variable interpolation happens.
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".
1173 Note: virtual methods can only be used on literal strings in CET, not in TT.
1175 You may also embed the current tags in strings (CET only).
1177 [% "[% 1 + 2 %]" | eval %] Prints "3"
1179 =item Array Constructs.
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.
1187 Note: virtual methods can only be used on array contructs in CET, not in TT.
1189 =item Quoted Array Constructs.
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.
1196 Note: this works in CET and is planned for TT3.
1198 =item Hash Constructs.
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.
1205 [% {Tom => 'You are Tom',
1206 Kay => 'You are Kay'}.$name %] Prints You are Tom
1208 Note: virtual methods can only be used on hash contructs in CET, not in TT.
1210 =item Regex Constructs.
1212 [% /foo/ %] Prints (?-xism:foo)
1213 [% a = /(foo)/i %][% "FOO".match(a).0 %] Prints FOO
1215 Note: this works in CET and is planned for TT3.
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.
1224 The following section shows some samples of expressions. For a full
1225 list of available operators, please see the section titled OPERATORS.
1227 [% 1 + 2 %] Prints 3
1228 [% 1 + 2 * 3 %] Prints 7
1229 [% (1 + 2) * 3 %] Prints 9
1231 [% x = 2 %] # assignments don't return anything
1232 [% (x = 2) %] Prints 2 # unless they are in parens
1234 [% x * (y - 1) %] Prints 4
1236 =head1 VIRTUAL METHODS
1238 The following is the list of builtin virtual methods and filters that
1239 can be called on each type of data.
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.
1248 Virtual methods are also made available via Virtual Objects which
1249 are discussed in a later section.
1251 =head2 SCALAR VIRTUAL METHODS AND FILTERS
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.
1259 In addition to the filters listed below, CET will automatically load
1260 Template::Filters and use them if Template::Toolkit is installed.
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
1266 Scalar virtual methods are also available through the "Text" virtual
1267 object (except for true filters such as eval and redirect).
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:
1275 You may set VMETHOD_FUNCTIONS to 0 to disable this behavior.
1281 [% item = 'foo' %][% item.0 %] Returns foo.
1283 Allows for scalars to mask as arrays (scalars already will, but this
1284 allows for more direct access).
1288 [% -1.abs %] Returns the absolute value
1292 [% pi = 4 * 1.atan2(1) %]
1294 Returns the arctangent. The item itself represents Y, the passed argument represents X.
1298 [% item.chunk(60).join("\n") %] Split string up into a list of chunks of text 60 chars wide.
1302 [% item.collapse %] Strip leading and trailing whitespace and collapse all other space to one space.
1306 [% item.cos %] Returns the cosine of the item.
1310 [% item.defined %] Always true - because the undef sub translates all undefs to ''.
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.
1320 This is a filter and is not available via the Text virtual object.
1324 Same as the eval filter.
1328 [% 1.exp %] Something like 2.71828182845905
1330 Returns "e" to the power of the item.
1334 Same as the redirect filter.
1338 [% item.fmt('%d') %]
1339 [% item.fmt('%6s') %]
1340 [% item.fmt('%*s', 6) %]
1342 Similar to format. Returns a string formatted with the passed pattern. Default pattern is %s.
1343 Opposite from of the sprintf vmethod.
1347 [% item.format('%d') %]
1348 [% item.format('%6s') %]
1349 [% item.format('%*s', 6) %]
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.
1357 [% item.hash %] Returns a one item hash with a key of "value" and a value of the item.
1364 Returns the decimal value of the passed hex numbers. Note that you
1365 may also just use [% 0xFF %].
1369 [% item.html %] Performs a very basic html encoding (swaps out &, <, > and " for the html entities)
1373 [% item.indent(3) %] Indent that number of spaces.
1375 [% item.indent("Foo: ") %] Add the string "Foo: " to the beginning of every line.
1379 [% item.int %] Return the integer portion of the value (0 if none).
1383 Same as the lower vmethod. Returns the lower cased version of the item.
1387 [% item.lcfirst %] Capitalize the leading letter.
1391 [% item.length %] Return the length of the string.
1395 [% item.list %] Returns a list with a single value of the item.
1399 [% 8.exp.log %] Equal to 8.
1401 Returns the natural log base "e" of the item.
1405 [% item.lower %] Return a lower-casified string.
1409 [% item.match("(\w+) (\w+)") %] Return a list of items matching the pattern.
1411 [% item.match("(\w+) (\w+)", 1) %] Same as before - but match globally.
1413 In CGI::Ex::Template and TT3 you can use regular expressions notation as well.
1415 [% item.match( /(\w+) (\w+)/ ) %] Same as before.
1417 [% item.match( m{(\w+) (\w+)} ) %] Same as before.
1421 [% item.null %] Do nothing.
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.
1433 [% item = 10; item.rand %] Returns a number greater or equal to 0 but less than 10.
1436 Note: This filter is not available as of TT2.15.
1440 [% item.remove("\s+") %] Same as replace - but is global and replaces with nothing.
1444 [% item.redirect("output_file.html") %]
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.
1449 This is a filter and is not available via the Text virtual object.
1453 [% item.repeat(3) %] Repeat the item 3 times
1455 [% item.repeat(3, ' | ') %] Repeat the item 3 times separated with ' | '
1459 [% item.replace("\s+", " ") %] Globally replace all space with
1461 [% item.replace("foo", "bar", 0) %] Replace only the first instance of foo with bar.
1463 [% item.replace("(\w+)", "($1)") %] Surround all words with parenthesis.
1465 In CGI::Ex::Template and TT3 you may also use normal regular expression notation.
1467 [% item.replace(/(\w+)/, "($1)") %] Same as before.
1471 [% item.search("(\w+)") %] Tests if the given pattern is in the string.
1473 In CGI::Ex::Template and TT3 you may also use normal regular expression notation.
1475 [% item.search(/(\w+)/, "($1)") %] Same as before.
1479 [% item.sin %] Returns the sine of the item.
1483 [% item.size %] Always returns 1.
1487 [% item.split %] Returns an arrayref from the item split on " "
1489 [% item.split("\s+") %] Returns an arrayref from the item split on /\s+/
1491 [% item.split("\s+", 3) %] Returns an arrayref from the item split on /\s+/ splitting until 3 elements are found.
1493 In CGI::Ex::Template and TT3 you may also use normal regular expression notation.
1495 [% item.split( /\s+/, 3 ) %] Same as before.
1499 [% item = "%d %d" %]
1500 [% item.sprintf(7, 8) %]
1502 Uses the pattern stored in self, and passes it to sprintf with the passed arguments.
1503 Opposite from the fmt vmethod.
1509 Returns the square root of the number.
1513 Calls the perl srand function to set the interal random seed. This
1514 will affect future calls to the rand vmethod.
1518 [% item.stderr %] Print the item to the current STDERR handle.
1522 [% item.substr(i) %] Returns a substring of item starting at i and going to the end of the string.
1524 [% item.substr(i, n) %] Returns a substring of item starting at i and going n characters.
1528 [% item.trim %] Strips leading and trailing whitespace.
1532 Same as the upper command. Returns upper cased string.
1536 [% item.ucfirst %] Lower-case the leading letter.
1540 [% item.upper %] Return a upper cased string.
1544 [% item.uri %] Perform a very basic URI encoding.
1548 [% item.url %] Perform a URI encoding - but some characters such
1549 as : and / are left intact.
1553 =head2 LIST VIRTUAL METHODS
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
1559 Additionally, list virtual methods can be accessed via the List
1566 [% mylist.fmt('%s', ', ') %]
1567 [% mylist.fmt('%6s', ', ') %]
1568 [% mylist.fmt('%*s', ', ', 6) %]
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.
1576 [% mylist.first(3) %] Returns a list of the first 3 items in the list.
1580 [% mylist.grep("^\w+\.\w+$") %] Returns a list of all items matching the pattern.
1584 [% mylist.hash %] Returns a hashref with the array indexes as keys and the values as values.
1588 [% mylist.join %] Joins on space.
1589 [% mylist.join(", ") Joins on the passed argument.
1593 [% mylist.last(3) %] Returns a list of the last 3 items in the list.
1597 [% mylist.list %] Returns a reference to the list.
1601 [% mylist.max %] Returns the last item in the array.
1605 [% mylist.merge(list2) %] Returns a new list with all defined items from list2 added.
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.
1614 [% mylist.pop %] Removes and returns the last element from the arrayref (the stash is modified).
1618 [% mylist.push(23) %] Adds an element to the end of the arrayref (the stash is modified).
1622 [% mylist.pick %] Returns a random item from the list.
1623 [% ['a' .. 'z'].pick %]
1625 An additional numeric argument is how many items to return.
1627 [% ['a' .. 'z'].pick(8).join('') %]
1629 Note: This filter is not available as of TT2.15.
1633 [% mylist.reverse %] Returns the list in reverse order.
1637 [% mylist.shift %] Removes and returns the first element of the arrayref (the stash is modified).
1641 [% mylist.size %] Returns the number of elements in the array.
1645 [% mylist.slice(i, n) %] Returns a list from the arrayref beginning at index i and continuing for n items.
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.
1654 [% mylist.splice(i, n) %] Removes items from array beginning at i and continuing for n items.
1656 [% mylist.splice(i, n, list2) %] Same as before, but replaces removed items with the items
1661 [% mylist.unique %] Return a list of the unique items in the array.
1665 [% mylist.unshift(23) %] Adds an item to the beginning of the arrayref.
1669 =head2 HASH VIRTUAL METHODS
1671 The following methods can be called on hash type data structures:
1673 Additionally, list virtual methods can be accessed via the Hash
1680 [% myhash.fmt('%s => %s', "\n") %]
1681 [% myhash.fmt('%4s => %5s', "\n") %]
1682 [% myhash.fmt('%*s => %*s', "\n", 4, 5) %]
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.
1690 [% myhash.defined('a') %] Checks if a is defined in the hash.
1694 [% myhash.delete('a') %] Deletes the item from the hash.
1696 Unlink Perl the value is not returned. Multiple values may be passed
1697 and represent the keys to be deleted.
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.
1706 [% myhash.exists('a') %] Checks if a is in the hash.
1710 [% myhash.hash %] Returns a reference to the hash.
1714 [% myhash.import(hash2) %] Overlays the keys of hash2 over the keys of myhash.
1718 [% myhash.item(key) %] Returns the hashes value for that key.
1722 [% myhash.items %] Returns a list of the key and values (flattened hash)
1726 [% myhash.keys.join(', ') %] Returns an arrayref of the keys of the hash.
1730 [% myhash.list %] Returns an arrayref with the hash as a single value (subject to change).
1734 [% myhash.pairs %] Returns an arrayref of hashrefs where each hash contains {key => $key, value => $value}
1735 for each value of the hash.
1739 [% myhash.nsort.join(", ") %] Returns a numerically sorted list of the keys.
1743 [% myhash.size %] Returns the number of key/value pairs in the hash.
1747 [% myhash.sort.join(", ") Returns an alphabetically sorted list.
1751 [% myhash.values.join(', ') %] Returns an arrayref of the values of the hash.
1755 =head1 VIRTUAL OBJECTS
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).
1764 [% a = "foo"; a.length %] => 3
1766 [% a = "foo"; Text.length(a) %] => 3
1768 [% a = Text.new("foo"); a.length %] => 3
1771 [% a = [1 .. 30]; a.size %] => 30
1773 [% a = [1 .. 30]; List.size(a) %] => 30
1775 [% a = List.new(1 .. 30); a.size %] => 30
1778 [% a = {a => 1, b => 2}; a.size %] => 2
1780 [% a = {a => 1, b => 2}; Hash.size(a) %] => 2
1782 [% a = Hash.new({a => 1, b => 2}); a.size %] => 2
1784 [% a = Hash.new(a => 1, b => 2); a.size %] => 2
1786 [% a = Hash.new(a = 1, b = 2); a.size %] => 2
1788 [% a = Hash.new('a', 1, 'b', 2); a.size %] => 2
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.
1794 Additionally, you can use all of the Virtual object methods with
1799 | List.join(", ") %] => a, b
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.
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.
1808 =head1 DIRECTIVES (TT Style)
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.
1816 [% IF 1 %]One[% END %]
1817 [% FOREACH a = [1 .. 3] %]
1821 [% SET a = 1 %][% SET a = 2 %][% GET a %]
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
1832 [% SET a = 1 ; SET a = 2 ; GET a %]
1839 IF 0 # is a post-operative
1843 IF 0 # it is block based
1848 The following is the list of directives.
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.
1858 [% BLOCK foo %]Some text[% END %]
1866 [% BLOCK foo %]Some text[% END %]
1872 Anonymous BLOCKS can be used for capturing.
1874 [% a = BLOCK %]Some text[% END %][% a %]
1880 Anonymous BLOCKS can be used with macros.
1885 Alias for LAST. Used for exiting FOREACH and WHILE loops.
1889 Calls the variable (and any underlying coderefs) as in the GET method, but
1890 always returns an empty string.
1894 Used with the SWITCH directive. See the L</"SWITCH"> directive.
1898 Used with the TRY directive. See the L</"TRY"> directive.
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.
1908 Allow for changing the value of some compile time and runtime configuration
1916 The following compile time configuration options may be set:
1926 The following runtime configuration options may be set:
1931 If non-named parameters as passed, they will show the current configuration:
1933 [% CONFIG ANYCASE, PRE_CHOMP %]
1935 CONFIG ANYCASE = undef
1936 CONFIG PRE_CHOMP = undef
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.
1944 [% DEBUG format '($file) (line $line) ($text)' %]
1950 Similar to SET, but only sets the value if a previous value was not
1951 defined or was zero length.
1953 [% DEFAULT foo = 'bar' %][% foo %] => 'bar'
1955 [% foo = 'baz' %][% DEFAULT foo = 'bar' %][% foo %] => 'baz'
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).
1963 The output also includes the current file and line number that the
1964 DUMP directive was called from.
1966 See the DUMP configuration item for ways to customize and control
1967 the output available to the DUMP directive.
1969 [% DUMP %] # dumps everything
1975 Used with the IF directive. See the L</"IF"> directive.
1979 Used with the IF directive. See the L</"IF"> directive.
1983 Used to end a block directive.
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.
1992 TODO - enumerate the at least 7 ways to pass and use filters.
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.
2004 Used with the TRY directive. See the L</"TRY"> directive.
2012 Allows for iterating over the contents of any arrayref. If the variable is not an
2013 arrayref, it is automatically promoted to one.
2015 [% FOREACH i IN [1 .. 3] %]
2016 The variable i = [% i %]
2020 [% FOREACH j IN a %]
2021 The variable j = [% j %]
2034 You can also use the "=" instead of "IN" or "in".
2036 [% FOREACH i = [1 .. 3] %]
2037 The variable i = [% i %]
2042 Setting into a variable is optional.
2045 [% FOREACH a %] Hi [% END %]
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
2055 [% FOREACH [{a => 1}, {a => 2}] %]
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".
2068 The loop variable provides the following information during a FOREACH:
2070 index - the current index
2071 max - the max index of the list
2072 size - the number of items in the list
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
2082 [% FOREACH [1 .. 3] %] [% loop.count %]/[% loop.size %] [% END %]
2088 The iterator is also available using a plugin. This allows for access
2089 to multiple "loop" variables in a nested FOREACH directive.
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 %])
2105 FOREACH may also be used as a post operative directive.
2107 [% "$i" FOREACH i = [1 .. 5] %] => 12345
2111 Return the value of a variable or expression.
2115 The GET keyword may be omitted.
2119 [% 7 + 2 - 3 %] => 6
2121 See the section on VARIABLES.
2123 =item C<IF (IF / ELSIF / ELSE)>
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.
2132 [% IF a == b %]A equaled B[% END %]
2136 [%- ELSIF a == c -%]
2139 Couldn't determine that A equaled anything.
2142 IF may also be used as a post operative directive.
2144 [% 'A equaled B' IF a == b %]
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.
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.
2156 [% INCLUDE path/to/template.html %]
2158 [% INCLUDE "path/to/template.html" %]
2160 [% file = "path/to/template.html" %]
2163 [% BLOCK foo %]This is foo[% END %]
2166 Arguments may also be passed to the template:
2168 [% INCLUDE "path/to/template.html" a = "An arg" b = "Another arg" %]
2170 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
2171 or RELATIVE configuration items are set.
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.
2177 [% INCLUDE "path/to/template.html",
2178 "path/to/template2.html" a = "An arg" b = "Another arg" %]
2182 Insert the contents of a file without template parsing.
2184 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
2185 or RELATIVE configuration items are set.
2187 Multiple filenames can be passed by separating them with a plus, a space,
2188 or commas (TT2 doesn't support the comma).
2190 [% INSERT "path/to/template.html",
2191 "path/to/template2.html" %]
2195 Used to exit out of a WHILE or FOREACH loop.
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.
2204 [% var a = [{b => 1}, {b => 2}, {b => 3}] %]
2206 [% LOOP a %] ([% b %]) [% END %]
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.
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.
2222 Takes a directive and turns it into a variable that can take arguments.
2224 [% MACRO foo(i, j) BLOCK %]You passed me [% i %] and [% j %].[% END %]
2226 [%~ foo("a", "b") %]
2231 You passed me a and b.
2232 You passed me 1 and 2.
2236 [% MACRO bar(max) FOREACH i = [1 .. max] %]([% i %])[% END %]
2246 Used to define variables that will be available via either the
2247 template or component namespace.
2249 Once defined, they cannot be overwritten.
2251 [% template.foobar %]
2252 [%~ META foobar = 'baz' %]
2253 [%~ META foobar = 'bing' %]
2261 Used to go to the next iteration of a WHILE or FOREACH loop.
2265 Only available if the EVAL_PERL configuration item is true (default is false).
2267 Allow eval'ing the block of text as perl. The block will be parsed and then eval'ed.
2272 print "The variable \$a was \"$a\"";
2273 $stash->set('b', "FooBar");
2279 The variable $a was "BimBam"
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.
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.
2293 [% PROCESS path/to/template.html %]
2295 [% PROCESS "path/to/template.html" %]
2297 [% file = "path/to/template.html" %]
2300 [% BLOCK foo %]This is foo[% END %]
2303 Arguments may also be passed to the template:
2305 [% PROCESS "path/to/template.html" a = "An arg" b = "Another arg" %]
2307 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
2308 or RELATIVE configuration items are set.
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.
2314 [% PROCESS "path/to/template.html",
2315 "path/to/template2.html" a = "An arg" b = "Another arg" %]
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.
2325 Used to exit the innermost block or template and continue processing
2326 in the surrounding block or template.
2330 Used to set variables.
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"
2341 Used to exit the entire process method (out of all blocks and templates).
2342 No content will be processed beyond this point.
2346 Allow for SWITCH and CASE functionality.
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
2359 You said hi or hello
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.
2372 The named tags are (duplicated from TT):
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
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.
2390 [% TAGS [<] [>] %] matches "[<] tag [>]"
2392 [% TAGS '[<]' '[>]' %] matches "[<] tag [>]"
2394 [% TAGS "[<]" "[>]" %] matches "[<] tag [>]"
2396 [% TAGS /[<]/ /[>]/ %] matches "< tag >"
2398 [% TAGS ** ** %] matches "** tag **"
2400 [% TAGS /**/ /**/ %] Throws an exception.
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.
2407 [% THROW mytypes.sometime 'Something happened' arg1 => val1 %]
2409 See the TRY directive for examples of usage.
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).
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.
2426 Nothing bad happened.
2430 This section runs no matter what happens.
2435 Nothing bad happened.
2436 This section runs no matter what happens.
2441 [% THROW "Something happened" %]
2444 Error.type: [% error.type %]
2445 Error.info: [% error.info %]
2447 This section runs no matter what happens.
2452 Error: undef error - Something happened
2454 Error.info: Something happened
2455 This section runs no matter what happens.
2457 You can give the error a type and more information including named arguments.
2458 This information replaces the "info" property of the exception.
2461 [% THROW foo.bar "Something happened" "grrrr" foo => 'bar' %]
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 %]
2472 Would print something like:
2474 Error: foo.bar error - HASH(0x82a395c)
2476 Error.info: HASH(0x82a395c)
2477 Error.info.0: Something happened
2479 Error.info.args.0: Something happened
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.
2489 [% THROW foo.bar "Something happened" %]
2493 Caught default - but rethrew.
2501 Caught anything else.
2506 Caught default - but rethrew.
2512 Same as IF but condition is negated.
2514 [% UNLESS 0 %]hi[% END %] => hi
2516 Can also be a post operative directive.
2520 Allows for loading a Template::Toolkit style plugin.
2522 [% USE iter = Iterator(['foo', 'bar']) %]
2523 [%~ iter.get_first %]
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.
2535 [% USE Iterator(['foo', 'bar', 'baz']) %]
2536 [%~ Iterator.get_first %]
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).
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.
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).
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
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+', ' ') %]
2572 $VAR1 = [ [ undef, '*', '2', '3' ], 0 ];
2574 See the PLUGIN_BASE, and PLUGINS configuration items.
2576 See the documentation for Template::Manual::Plugins.
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.
2588 Will process a block of code while a condition is true.
2604 [% WHILE (i = i - 1) %]
2614 Note that (f = f - 1) is a valid expression that returns the value
2615 of the assignment. The parenthesis are not optional.
2617 WHILE has a built in limit of 1000 iterations. This is controlled by the
2618 global variable $WHILE_MAX in CGI::Ex::Template.
2620 WHILE may also be used as a post operative directive.
2622 [% "$i" WHILE (i = i + 1) < 7 %] => 123456
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
2630 [% WRAPPER foo b = 23 %]
2631 My content to be processed ([% b %]).[% a = 2 %]
2643 My content to be processed (23).
2646 The WRAPPER directive may also be used as a post operative directive.
2648 [% BLOCK baz %]([% content %])[% END -%]
2649 [% "foobar" WRAPPER baz %]
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
2662 [% WRAPPER "path/to/outer.html",
2663 "path/to/inner.html" a = "An arg" b = "Another arg" %]
2668 =head1 DIRECTIVES (HTML::Template Style)
2670 HTML::Template templates use directives that look similar to the
2673 <TMPL_VAR NAME="foo">
2675 <TMPL_IF NAME="bar">
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.
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
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
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}
2698 <TMPL_IF foo> Prints FOO if foo is true
2702 <TMPL_UNLESS foo> Prints FOO unless foo is true
2706 <TMPL_INCLUDE NAME="foo.ht"> Includes the template in "foo.ht"
2708 <TMPL_LOOP foo> Iterates on the arrayref foo
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.
2716 <TMPL_MACRO bar(n) BLOCK>You said <TMPL_VAR n></TMPL_MACRO>
2717 <TMPL_GET bar("hello")>
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.
2723 Escape value | Type of escape
2724 ---------------------------------
2725 HTML, 1 | HTML encoding
2727 JS | basic javascript encoding (\n, \r, and \")
2728 NONE, 0 | No encoding (default).
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
2734 <TMPL_VAR foo DEFAULT="Foo was false">
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
2747 The dot operator. Allows for accessing sub-members, methods, or
2748 virtual methods of nested data structures.
2750 my $obj->process(\$content, {a => {b => [0, {c => [34, 57]}]}}, \$output);
2752 [% a.b.1.c.0 %] => 34
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 "|".
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.
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.
2778 The following two cases will do the same thing.
2782 [% foo FILTER html %]
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.
2788 A TT2 sample that would break in CGI::Ex::Template or TT3 is:
2790 [% PROCESS foo a = b | html %]
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.
2797 A simple fix is to do any of the following:
2799 [% PROCESS foo a = b FILTER html %]
2801 [% | html %][% PROCESS foo a = b %][% END %]
2803 [% FILTER html %][% PROCESS foo a = b %][% END %]
2805 This shouldn't be too much hardship and offers the great return of disambiguating
2806 virtual method access.
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.
2813 [% f = 7 ; foo = \f ; f = 8 ; foo %] => 8
2815 [% foo = \f.g.h.i.j.k; f.g.h.i.j.k = 7; foo %] => 7
2817 [% f = "abcd"; foo = \f.replace("ab", "-AB-") ; foo %] => -AB-cd
2819 [% f = "abcd"; foo = \f.replace("bc") ; foo("-BC-") %] => a-BC-d
2821 [% f = "abcd"; foo = \f.replace ; foo("cd", "-CD-") %] => ab-CD-
2825 Pre and post increment and decrement. My be used as either a prefix
2826 or postfix operator.
2828 [% ++a %][% ++a %] => 12
2830 [% a++ %][% a++ %] => 01
2832 [% --a %][% --a %] => -1-2
2834 [% a-- %][% a-- %] => 0-1
2838 Right associative binary. X raised to the Y power. This isn't available in TT 2.15.
2844 Prefix not. Negation of the value.
2848 Prefix minus. Returns the value multiplied by -1.
2850 [% a = 1 ; b = -a ; b %] => -1
2854 Left associative binary. Multiplication.
2858 Left associative binary. Division. Note that / is floating point division, but div and
2859 DIV are integer division.
2866 Left associative binary. Modulus.
2872 Left associative binary. Addition.
2876 Left associative binary. Minus.
2880 Left associative binary. String concatenation.
2882 [% "a" ~ "b" %] => ab
2884 =item C<< < > <= >= >>
2886 Non associative binary. Numerical comparators.
2888 =item C<lt gt le ge>
2890 Non associative binary. String comparators.
2894 Non associative binary. String equality test.
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.
2904 The HTML::Template syntaxes default V2EQUALS to 0 which means
2905 that it will test for numeric equality just as you would normally
2908 In either case - you should always use "eq" when you mean "eq".
2909 The V2EQUALS will most likely eventually default to 0.
2913 Non associative binary. String non-equality test.
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.
2923 The HTML::Template syntaxes default V2EQUALS to 0 which means
2924 that it will test for numeric non-equality just as you would
2927 In either case - you should always use "ne" when you mean "ne".
2928 The V2EQUALS will most likely eventually default to 0.
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.
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.
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.
2945 [% 2 && 3 && 4 %] => 4
2949 Right associative binary. Or. The first true value is returned.
2951 [% 0 || '' || 7 %] => 7
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))).
2960 Non associative binary. Range creator. Returns an arrayref containing the values
2961 between and including the first and last arguments.
2963 [% t = [1 .. 5] %] => variable t contains an array with 1,2,3,4, and 5
2965 It is possible to place multiple ranges in the same [] constructor. This is not available in TT.
2967 [% t = [1..3, 6..8] %] => variable t contains an array with 1,2,3,6,7,8
2969 The .. operator is the only operator that returns a list of items.
2973 Ternary - right associative. Can be nested with other ?: pairs.
2975 [% 1 ? 2 : 3 %] => 2
2976 [% 0 ? 2 : 3 %] => 3
2978 =item C<*= += -= /= **= %= ~=>
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.
2985 [% a = 2 %][% a += 3 %] --- [% a %] => --- 5 # is handled by SET
2986 [% a = 2 %][% (a += 3) %] --- [% a %] => 5 --- 5
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.
2994 [% a = 1 %] --- [% a %] => --- 1 # is handled by SET
2995 [% (a = 1) %] --- [% a %] => 1 --- 1
2999 Prefix. Lower precedence version of the '!' operator.
3003 Left associative. Lower precedence version of the '&&' operator.
3007 Right associative. Lower precedence version of the '||' operator.
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.
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.
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.
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.
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:
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
3051 Don't do any chomping. The "+" sign is used to indicate CHOMP_NONE.
3067 =item CHOMP_ONE (formerly known as CHOMP_ALL)
3069 Delete any whitespace up to the adjacent newline. The "-" is used to indicate CHOMP_ONE.
3083 =item CHOMP_COLLAPSE
3085 Collapse adjacent whitespace to a single space. The "=" is used to indicate CHOMP_COLLAPSE.
3099 Remove all adjacent whitespace. The "~" is used to indicate CHOMP_GREEDY.
3111 =head1 CONFIGURATION (TT STYLE)
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.
3117 Items may be passed in upper or lower case.
3119 These variables should be passed to the "new" constructor.
3121 my $obj = CGI::Ex::Template->new(
3122 VARIABLES => \%hash_of_variables,
3134 Boolean. Default false. Are absolute paths allowed for included files.
3138 Allow directive matching to be case insensitive.
3140 [% get 23 %] prints 23 with ANYCASE => 1
3144 Boolean. Default 1. Clear blocks that were set during the process method.
3148 A hashref of blocks that can be used by the process method.
3151 block_1 => sub { ... }, # coderef that returns a block
3152 block_2 => 'A String', # simple string
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.
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.
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
3174 Extension to add to stored compiled template filenames. Default undef.
3178 Hashref. Used to define variables that will be "folded" into the
3179 compiled template. Variables defined here cannot be overridden.
3181 CONSTANTS => {my_constant => 42},
3183 A template containing:
3185 [% constants.my_constant %]
3187 Will have the value 42 compiled in.
3189 Constants defined in this way can be chained as in [%
3190 constant.foo.bar.baz %].
3192 =item CONSTANT_NAMESPACE
3194 Allow for setting the top level of values passed in CONSTANTS. Default
3195 value is 'constants'.
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 ",").
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.
3208 Either of the following would turn on undef and directive debugging:
3210 DEBUG => 'undef, dirs', # preferred
3212 DEBUG => DEBUG_UNDEF | DEBUG_DIRS, # constants from Template::Constants
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
3222 The name of a default template file to use if the passed one is not found.
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.
3231 Configures the behavior of the DUMP tag. May be set to 0, a hashref,
3232 or another true value. Default is true.
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.
3237 IF set to a true value (or undefined) then DUMP directives will operate.
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.
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
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.
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
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:
3269 return "\$VAR1 =\n".YAML::Dump(shift);
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.
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.
3285 =item Sortkeys, Useqq, Ident, Pad, etc
3287 Any of the Data::Dumper configuration items may be passed.
3293 Set a string to use as the closing delimiter for TT. Default is "%]".
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
3305 my $t = CGI::Ex::Template->new({
3306 ERROR => 'general/catch_all_errors.html',
3309 my $t = CGI::Ex::Template->new({
3311 default => 'general/catch_all_errors.html',
3312 foo => 'catch_all_general_foo_errors.html',
3313 'foo.bar' => 'catch_foo_bar_errors.html',
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.
3324 Same as the ERROR configuration item. Both may be used interchangably.
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.
3335 Allow for passing in TT style 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],
3345 1 ([% a | filter1 %])
3346 2 ([% a | filter2 %])
3347 3 ([% a | filter3 %])
3350 my $obj = CGI::Ex::Template->new(FILTERS => $filters);
3351 $obj->process(\$str) || die $obj->error;
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.
3367 A string or an arrayref or coderef that returns an arrayref that
3368 contains directories to look for files included by processed
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.
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).
3383 [% IF 1 %]The variable $variable had a value ${var.value}[% END %]
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
3391 =item MAX_EVAL_RECURSE (CET only)
3393 Will use $CGI::Ex::Template::MAX_EVAL_RECURSE if not present. Default is 50.
3394 Prevents runaway on the following:
3396 [% f = "[% f|eval %]" %][% f|eval %]
3398 =item MAX_MACRO_RECURSE (CET only)
3400 Will use $CGI::Ex::Template::MAX_MACRO_RECURSE if not present. Default is 50.
3401 Prevents runaway on the following:
3403 [% MACRO f BLOCK %][% f %][% END %][% f %]
3407 No Template::Namespace::Constants support. Hashref of hashrefs representing
3408 constants that will be folded into the template at compile time.
3410 CGI::Ex::Template->new(NAMESPACE => {constants => {
3416 CGI::Ex::Template->new(CONSTANTS => {
3420 Any number of hashes can be added to the NAMESPACE hash.
3422 =item NEGATIVE_STAT_TTL (Not in TT)
3424 Defaults to STAT_TTL which defaults to $STAT_TTL which defaults to 1.
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.
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.
3437 See the process method for a listing of possible values.
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.
3447 A hashref of mappings of plugin modules.
3450 Iterator => 'Template::Plugin::Iterator',
3454 See the USE directive for more information.
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
3465 Set the type of chomping at the ending of a tag.
3466 See the section on chomping for more information.
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.
3474 This is useful for adding a global footer to all templates.
3478 Set the type of chomping at the beginning of a tag.
3479 See the section on chomping for more information.
3483 Same as the VARIABLES configuration item.
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.
3491 This is useful for adding a global header to all templates.
3495 Specify a file to use as the template rather than the one passed in
3496 to the ->process method.
3500 Boolean. Default false. Indicates that INCLUDED or PROCESSED files
3501 can refer to each other in a circular manner. Be careful about recursion.
3505 Boolean. Default false. If true, allows filenames to be specified
3506 that are relative to the currently running process.
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.
3517 Set a string to use as the opening delimiter for TT. Default is "[%".
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.
3527 =item SYNTAX (not in TT)
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).
3534 The syntax may be passed in upper or lower case.
3536 The available choices are:
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
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
3549 The following is a sample of HTML::Template interface usage parsing
3550 a Template::Toolkit style document.
3552 my $obj = CGI::Ex::Template->new(filename => 'my/template.tt'
3554 $obj->param(\%swap);
3557 The following is a sample of Template::Toolkit interface usage parsing
3558 a HTML::Template::Expr style document.
3560 my $obj = CGI::Ex::Template->new(SYNTAX => 'hte');
3561 $obj->process('my/template.ht', \%swap);
3563 You can use the define_syntax method to add another custom syntax to
3564 the list of available options.
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.
3573 Remove leading and trailing whitespace from blocks and templates.
3574 This operation is performed after all enclosed template tags have
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.
3587 You can also sub class the module and override the undefined_any method.
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 %]).
3597 You can also sub class the module and override the undefined_get method.
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.
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}"
3618 Default 1 in TT syntaxes, defaults to 0 in HTML::Template syntaxes.
3620 If set to 1 then "==" is an alias for "eq" and "!= is an alias for
3623 [% CONFIG V2EQUALS => 1 %][% ('7' == '7.0') || 0 %]
3624 [% CONFIG V2EQUALS => 0 %][% ('7' == '7.0') || 0 %]
3633 Restores the behavior of the pipe operator to be compatible with TT2.
3637 [%- BLOCK a %]b is [% b %]
3639 [%- PROCESS a b => 237 | repeat(2) %]
3641 # output of block "a" with b set to 237 is passed to the repeat(2) filter
3646 With V2PIPE = 0 (default)
3648 [%- BLOCK a %]b is [% b %]
3650 [% PROCESS a b => 237 | repeat(2) %]
3652 # b set to 237 repeated twice, and b passed to block "a"
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.
3662 =item VMETHOD_FUNCTIONS
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:
3670 You may set VMETHOD_FUNCTIONS to 0 to disable this behavior.
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).
3680 my $t = CGI::Ex::Template->new(
3681 WRAPPER => ['my/wrappers/outer.html', 'my/wrappers/inner.html'],
3684 Content generated by the PRE_PROCESS and POST_PROCESS will come before
3685 and after (respectively) the content generated by the WRAPPER
3688 See the WRAPPER direcive for more examples of how wrappers are construted.
3692 =head1 CONFIGURATION (HTML::Template STYLE)
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.
3701 Items may be passed in upper or lower case.
3703 These variables should be passed to the "new" constructor.
3705 my $obj = CGI::Ex::Template->new(
3707 source => 'my/template.ht',
3708 die_on_bad_params => 1,
3709 loop_context_vars => 1,
3719 Can be one of filename, filehandle, arrayref, or scalarref. Indicates what type
3720 of input is in the "source" configuration item.
3724 Stores where to read the input file. The type is specified in the "type"
3729 Indicates a filename to read the template from. Same as putting the
3730 filename in the "source" item and setting "type" to "filename".
3732 Must be set to enable caching.
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".
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".
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".
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.
3764 Same as with cache enabled, but will not check if the document has
3769 If set to 1, will cache the compiled document on the file system. If
3770 true, file_cache_dir must be set.
3772 =item file_cache_dir
3774 The directory where to store cached documents when file_cache is true.
3775 This is similar to the TT compile_dir option.
3777 =item double_file_cache
3779 Uses a combination of file_cache and cache.
3783 Same as INCLUDE_PATH when using the process method.
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
3791 =item case_sensitive
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.
3797 =item loop_context_vars
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:
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
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.
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.
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.
3823 =item default_escape
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.
3832 =head1 UNSUPPORTED HT CONFIGURATION
3836 =item die_on_bad_params
3838 CET does not resolve variables until the template is output.
3844 CET is strict on parsing HT documents.
3846 =item shared_cache, double_cache
3848 CET doesn't have shared caching. Yet.
3850 =item search_path_on_include
3852 CET will check the full path array on each include.
3856 The HTML::Template style options are included here, but you
3857 can use the TT style DEBUG and DUMP directives to do intropection.
3861 CET uses TT's recursion protection.
3865 CET doesn't offer these.
3869 =head1 UNSUPPORTED TT2 CONFIGURATION
3873 =item LOAD_TEMPLATES
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.
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.
3889 Full support is offered for the PLUGINS and LOAD_PERL configuration items.
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.
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.
3902 Full support is offered for the FILTERS configuration item.
3906 This option is used by the LOAD_TEMPLATES and LOAD_PLUGINS options and
3907 is not applicable in CGI::Ex::Template.
3911 CGI::Ex::Template has no concept of service (theoretically the CGI::Ex::Template
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.
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.
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.
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.
3943 =head1 VARIABLE PARSE TREE
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).
3953 The following table shows a variable or expression and the corresponding parsed tree
3954 (this is what the parse_expr method would return).
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]
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 ]
3982 Some notes on the parsing.
3984 Operators are parsed as part of the variable and become part of the variable tree.
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.
3991 Parenthesis () can be used at any point in an expression to disambiguate precedence.
3993 "Variables" that appear to be literal strings or literal numbers
3994 are returned as the literal (no operator tree).
3996 The following perl can be typed at the command line to view the parsed variable tree:
3998 perl -e 'use CGI::Ex::Template; print CGI::Ex::Template::dump_parse_expr("foo.bar + 2")."\n"'
4000 Also the following can be included in a template to view the output in a template:
4002 [% USE cet = CGI::Ex::Template %]
4003 [%~ cet.dump_parse_expr('foo.bar + 2').replace('\s+', ' ') %]
4006 =head1 SEMI PUBLIC METHODS
4008 The following list of methods are other interesting methods of CET that
4009 may be re-implemented by subclasses of CET.
4015 This method allows for returning a Data::Dumper dump of a parsed
4016 template. It is mainly used for testing.
4018 =item C<dump_parse_expr>
4020 This method allows for returning a Data::Dumper dump of a parsed
4021 variable. It is mainly used for testing.
4025 Creates an exception object blessed into the package listed in
4026 $CGI::Ex::Template::PACKAGE_EXCEPTION.
4028 =item C<execute_tree>
4030 Executes a parsed tree (returned from parse_tree)
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
4040 =item C<include_filename>
4042 Takes a file path, and resolves it into the full filename using
4043 paths from INCLUDE_PATH or INCLUDE_PATHS.
4047 Resolves the file passed, and then returns its contents.
4049 =item C<list_filters>
4051 Dynamically loads the filters list from Template::Filters when a filter
4052 is used that is not natively implemented in CET.
4054 =item C<list_plugins>
4056 Returns an arrayref of modules that are under a base Namespace.
4058 my @modules = @{ $self->list_plugins({base => 'Template::Plugins'}) }:
4060 =item C<load_parsed_tree>
4062 Given a filename or a string reference will return a parsed document
4063 hash that contains the parsed tree.
4065 my $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");
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.
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.
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
4085 =item C<set_variable>
4087 Used to set a variable. Expects a variable identity array and the value to set. It
4088 will autovifiy as necessary.
4092 Creates an exception object from the arguments and dies.
4094 =item C<undefined_any>
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.
4102 =item C<undefined_get>
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.
4111 =head1 OTHER UTILITY METHODS
4113 The following is a brief list of other methods used by CET. Generally, these
4114 shouldn't be overwritten by subclasses.
4118 =item C<apply_precedence>
4120 Allows for parsed operator array to be translated to a tree based
4121 upon operator precedence.
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.
4130 Used to get debug info on a directive if DEBUG_DIRS is set.
4134 Methods by these names implement filters that are more complex than one liners.
4136 =item C<get_line_number_by_index>
4138 Used to turn string index position into line number
4140 =item C<interpolate_node>
4142 Used for parsing text nodes for dollar variables when interpolate is on.
4146 Methods by these names are used by parse_tree to parse the template. These are the grammar.
4150 Methods by these names are used by execute_tree to execute the parsed tree.
4152 =item C<play_operator>
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.
4162 Called by process and the PROCESS, INCLUDE and other directives.
4166 Reads contents of passed filename - throws file exception on error.
4168 =item C<split_paths>
4170 Used to split INCLUDE_PATH or other directives if an arrayref is not passed.
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.
4179 Methods by these names implement virtual methods that are more complex than oneliners.
4186 Paul Seamons <paul at seamons dot com>
4190 This module may be distributed under the same terms as Perl itself.