3 CGI::Ex::Template - Fast and lightweight TT2/3 template engine
7 my $t = CGI::Ex::Template->new(
8 INCLUDE_PATH => ['/path/to/templates'],
18 $t->process('my/template.tt', $swap)
21 ### Anything in the Template::Toolkit SYNOPSIS would fit here also
25 CGI::Ex::Template happened by accident (accidentally on purpose). The
26 CGI::Ex::Template (CET hereafter) was originally a part of the CGI::Ex
27 suite that performed simple variable interpolation. It used TT2 style
28 variables in TT2 style tags "[% foo.bar %]". That was all the
29 original CGI::Ex::Template did. This was fine and dandy for a couple
30 of years. In winter of 2005-2006 CET was revamped to add a few
31 features. One thing led to another and soon CET provided for most of
32 the features of TT2 as well as some from TT3. CGI::Ex::Template is a
33 full-featured implementation of the Template::Toolkit language.
35 CGI::Ex::Template (CET hereafter) is smaller, faster, uses less memory
36 and less CPU than TT2. However, it is most likely less portable, less
37 extendable, and probably has many of the bugs that TT2 has already massaged
38 out from years of bug reports and patches from a very active community
39 and mailing list. CET does not have a vibrant community behind it. Fixes
40 applied to TT2 will take longer to get into CET, should they get in at all.
41 An attempt will be made to follow updates made to TT2 to keep the two
42 in sync at a language level. There already has been, and it is expected that
43 there will continue to be code sharing between the two projects. (Acutally
44 I will try and keep applicable fixes in sync with TT).
46 Most of the standard Template::Toolkit documentation covering directives,
47 variables, configuration, plugins, filters, syntax, and vmethods should
48 apply to CET just fine (This pod tries to explain everything - but there is
49 too much). The section on differences between CET and TT will explain
50 what too look out for.
52 Note: A clarification on "faster". All templates are going to take
53 different amounts of time to process. Different types of DIRECTIVES
54 parse and play more quickly than others. The test script
55 samples/benchmark/bench_template.pl was used to obtain sample numbers.
56 In general the following statements are true:
58 If you load a new Template object each time and pass a filename, CET
59 is around 4 times faster.
61 If you load a new Template object and pass a string ref, CET
62 is around 3.5 times faster.
64 If you load a new Template object and use CACHE_EXT, CET
65 is around 1.5 times faster.
67 If you use a cached object with a cached in memory template,
68 then CET is 50% faster.
70 If you use Template::Stash::XS with a cached in memory template,
71 then CET is about as fast.
73 Using TT with a compiled-in-memory template is only 33
74 faster than CET with a new object compiling each time.
76 It is pretty hard to beat the speed of XS stash with compiled in
77 memory templates. Many systems don't have access to those so
78 CET may make more sense. Hopefully as TT is revised, many of the CET
79 speed advantages can be incorporated so that the core TT is just as
82 So should you use CGI::Ex::Template ? Well, try it out. It may
83 give you no visible improvement. Or it could.
88 The following section lists most of the publicly available methods. Some less
89 commonly used public methods are listed later in this document.
95 my $obj = CGI::Ex::Template->new({
96 INCLUDE_PATH => ['/my/path/to/content', '/my/path/to/content2'],
99 Arguments may be passed as a hash or as a hashref. Returns a CGI::Ex::Template object.
101 There are currently no errors during CGI::Ex::Template object creation.
105 This is the main method call for staring processing. Any errors that results in the
106 template being stopped processing will be stored and available via the ->error method.
108 Process takes three arguments.
110 $t->process($in, $swap, $out)
113 The $in argument can be any one of:
115 String containing the filename of the template to be processed. The filename should
116 be relative to INCLUDE_PATH. (See INCLUDE_PATH, ABSOLUTE, and RELATIVE configuration items).
117 In memory caching and file side caching are available for this type.
119 A reference to a scalar containing the contents of the template to be processed.
121 A coderef that will be called to return the contents of the template.
123 An open filehandle that will return the contents of the template when read.
125 The $swap argument should be hashref containing key value pairs that will be
126 available to variables swapped into the template. Values can be hashrefs, hashrefs
127 of hashrefs and so on, arrayrefs, arrayrefs of arrayrefs and so on, coderefs, objects,
128 and simple scalar values such as numbers and strings. See the section on variables.
130 The $out argument can be any one of:
132 undef - meaning to print the completed template to STDOUT.
134 String containing a filename. The completed template will be placed in the file.
136 A reference to a string. The contents will be appended to the scalar reference.
138 A coderef. The coderef will be called with the contents as a single argument.
140 An object that can run the method "print". The contents will be passed as
141 a single argument to print.
143 An arrayref. The contents will be pushed onto the array.
145 An open filehandle. The contents will be printed to the open handle.
147 Additionally - the $out argument can be configured using the OUTPUT configuration
150 =item C<process_simple>
152 Similar to the process method but with the following restrictions:
154 The $in parameter is limited to a filename or a reference a string containing the contents.
156 The $out parameter may only be a reference to a scalar string that output will be appended to.
158 Additionally, the following configuration variables will be ignored: VARIABLES,
159 PRE_DEFINE, BLOCKS, PRE_PROCESS, PROCESS, POST_PROCESS, AUTO_RESET, OUTPUT.
163 Should something go wrong during a "process" command, the error that occurred can
164 be retrieved via the error method.
166 $obj->process('somefile.html', {a => 'b'}, \$string_ref)
169 =item C<define_vmethod>
171 This method is available for defining extra Virtual methods or filters. This method is similar
172 to Template::Stash::define_vmethod.
178 Add WRAPPER config item
180 Add ERROR config item
182 =head1 HOW IS CGI::Ex::Template DIFFERENT
184 CET uses the same template syntax and configuration items
185 as TT2, but the internals of CET were written from scratch. In
186 addition to this, the following is a list of some of the ways that
187 configuration and syntax of CET different from that of TT.
191 Numerical hash keys work [% a = {1 => 2} %]
193 Quoted hash key interpolation is fine [% a = {"$foo" => 1} %]
195 Multiple ranges in same constructor [% a = [1..10, 21..30] %]
197 Constructor types can call virtual methods
199 [% a = [1..10].reverse %]
203 [% 123.length %] # = 3
205 [% 123.4.length %] # = 5
207 [% -123.4.length %] # = -5 ("." binds more tightly than "-")
215 Reserved names are less reserved
217 [% GET GET %] # gets the variable named "GET"
219 [% GET $GET %] # gets the variable who's name is stored in "GET"
221 Filters and SCALAR_OPS are interchangeable.
227 Pipe "|" can be used anywhere dot "." can be and means to call
230 [% a = {size => "foo"} %][% a.size %] # = foo
232 [% a = {size => "foo"} %][% a|size %] # = 1 (size of hash)
234 Pipe "|" and "." can be mixed.
236 [% "aa" | repeat(2) . length %] # = 4
238 Whitespace is less meaningful.
240 [% 2-1 %] # = 1 (fails in TT)
244 [% 2 ** 3 %] [% 2 pow 3 %] # = 8 8
246 FOREACH variables can be nested
248 [% FOREACH f.b = [1..10] ; f.b ; END %]
250 Note that nested variables are subject to scoping issues.
251 f.b will not be reset to its value before the FOREACH.
253 Post operative directives can be nested.
255 [% one IF two IF three %]
259 [% IF three %][% IF two %][% one %][% END %][% END %]
262 [% a = [[1..3], [5..7]] %][% i FOREACH i = j FOREACH j = a %] # = 123567
264 CATCH blocks can be empty.
266 CET does not generate Perl code. It generates an "opcode" tree.
268 CET uses storable for its compiled templates. If EVAL_PERL is off,
269 CET will not eval_string on ANY piece of information.
271 There is no context. CET provides a context object that mimics the
272 Template::Context interface for use by some TT filters, eval perl
275 There is no stash. CET only supports the variables passed in
276 VARIABLES, PRE_DEFINE, and those passed to the process method. CET
277 provides a stash object that mimics the Template::Stash interface for
278 use by some TT filters, eval perl blocks, and plugins.
280 There is no provider. CET uses the load_parsed_tree method to get and
283 There is no grammar. CET has its own built in grammar system.
285 There is no VIEW directive.
287 There are no references. (There was in initial beta tests, but it was decided
288 to remove the little used feature).
290 The DEBUG directive only understands DEBUG_DIRS (8) and DEBUG_UNDEF (2).
292 When debug dirs is on, directives on different lines separated by colons show the line they
293 are on rather than a general line range.
295 There is no ANYCASE configuration item. There was in initial beta tests, but it
296 was dropped in favor of consistent parsing syntax.
298 There is no V1DOLLAR configuration item. This is a TT version 1 compatibility item and
299 is not available in CET.
305 This section discusses how to use variables and expressions in the TT mini-language.
307 A variable is the most simple construct to insert into the TT mini language. A variable
308 name will look for the matching value inside CGI::Ex::Templates internal stash of variables
309 which is essentially a hash reference. This stash is initially populated by either passing
310 a hashref as the second argument to the process method, or by setting the "VARIABLES" or
311 "PRE_DEFINE" configuration variables.
313 ### some sample variables
318 some_code => sub { "You passed me (".join(', ', @_).")" },
322 c => [3, 1, 4, 1, 5, 9],
325 my_list => [20 .. 50],
326 cet => CGI::Ex::Template->new,
329 ### pass the variables into the CET process
330 $cet->process($template_name, \%vars)
333 ### pass the variables during object creation (will be available to every process call)
334 my $cet = CGI::Ex::Template->new(VARIABLES => \%vars);
336 =head1 GETTING VARIABLES
338 Once you have variables defined, they can be used directly in the template by using their name
339 in the stash. Or by using the GET directive.
345 Would print when processed:
351 To access members of a hashref or an arrayref, you can chain together the names using a ".".
354 [% my_list.0] [% my_list.1 %]
363 If the value of a variable is a code reference, it will be called. You can add a set of parenthesis
364 and arguments to pass arguments. Arguments are variables and can be as complex as necessary.
369 [% some_code(one, 2, 3) %]
376 You passed me (1, 2, 3).
378 If the value of a variable is an object, methods can be called using the "." operator.
382 [% cet.dump_parse('1 + 2').replace('\s+', ' ') %]
384 Would print something like:
386 CGI::Ex::Template=HASH(0x814dc28)
388 $VAR1 = [ \[ '+', '1', '2' ], 0 ];
390 Each type of data has virtual methods associated with them. Virtual methods
391 allow for access to common functions. For the full list of built in virtual
392 methods, please see the section titled VIRTUAL METHODS
396 [% some_data.c.join(" | ") %]
404 It is also possible to "interpolate" variable names using a "$". This allows for storing
405 the name of a variable inside another variable. If a variable name is a little
406 more complex, it can be embedded inside of "${" and "}".
410 [% ${some_data.vname} %]
412 [% some_data.${foo} %]
422 =head2 SETTING VARIABLES.
424 To define variables during processing, you can use the = operator. In most cases
425 this is the same as using the SET directive.
428 [% SET b = "Hello" %][% b %]
435 It is also possible to create arrayrefs and hashrefs.
438 [% b = {key1 => 'val1', 'key2' => 'val2'} %]
441 [% b.key1 %] [% b.key2 %]
448 It is possible to set multiple values at the same time.
453 [% a %] [% b %] [% c %]
459 It is also possible to unset variables, or to set members of
460 nested data structures.
475 =head1 LITERALS AND CONSTRUCTORS
477 The following are the types of literals allowed in CET. They can be used as arguments
478 to functions, in place of variables in directives, and in place of variables in expressions.
480 In CET it is also possible to call virtual methods on literal values.
484 =item Integers and Numbers.
486 [% 23423 %] Prints an integer.
487 [% 3.14159 %] Prints a number.
488 [% pi = 3.14159 %] Sets the value of the variable.
489 [% 3.13159.length %] Prints 7 (the string length of the number)
492 =item Single quoted string.
494 Returns the string. No variable interpolation happens.
496 [% 'foobar' %] Prints "foobar".
497 [% '$foo\n' %] Prints "$foo\\n". # the \\n is a literal "\" and a "\n"
498 [% 'That\'s nice' %] Prints "That's nice".
499 [% str = 'A string' %] Sets the value of str.
500 [% 'A string'.split %] Splits the string on ' ' and returns the list.
502 Note: virtual methods can only be used on literal strings in CET, not in TT.
504 =item Double quoted string.
506 Returns the string. Variable interpolation happens.
508 [% "foobar" %] Prints "foobar".
509 [% "$foo" %] Prints "bar" (assuming the value of foo is bar).
510 [% "${foo} %] Prints "bar" (assuming the value of foo is bar).
511 [% "foobar\n" %] Prints "foobar\n". # the \n is a newline.
512 [% str = "Hello" %] Sets the value of str.
513 [% "foo".replace('foo','bar') %] Prints "bar".
515 Note: virtual methods can only be used on literal strings in CET, not in TT.
517 =item Array Constructor.
519 [% [1, 2, 3] %] Prints something like ARRAY(0x8309e90).
520 [% [4, 5, 6].size %] Prints 3.
521 [% [7, 8, 9].reverse.0 %] Prints 9.
522 [% array1 = [1 .. 3] %] Sets the value of array1.
523 [% array2 = [foo, 'a', []] %] Sets the value of array2.
525 Note: virtual methods can only be used on array contructors in CET, not in TT.
527 =item Hash Constructor.
529 [% {foo => 'bar'} %] Prints something like HASH(0x8305880)
530 [% {a => 'A', b => 'B'}.size %] Prints 2.
531 [% {'a' => 'A', 'b' => 'B'}.size %] Prints 2.
532 [% hash = {foo => 'bar', c => {}} %] Sets the value of hash.
534 Note: virtual methods can only be used on hash contructors in CET, not in TT.
538 Expressions are one or more variables or literals joined together
539 operators. An expression can be used anywhere a variable can be used
540 with the exception of the variable name of SET, and the filename of
541 PROCESS, INCLUDE, WRAPPER, and INSERT.
543 The following section shows some samples of expressions. For a full list
544 of available operators, please see the section titled OPERATORS.
547 [% 1 + 2 * 3 %] Prints 7
548 [% (1 + 2) * 3 %] Prints 9
552 [% z = x * (y - 1) %] Prints 4
554 =head1 VIRTUAL METHODS
556 The following is the list of builtin virtual methods and filters that
557 can be called on each type of data.
559 In CGI::Ex::Template, the "|" operator can be used to call virtual
560 methods just the same way that the "." operator can. The main
561 difference between the two is that on access to hashrefs or objects,
562 the "|" means to always call the virtual method or filter rather than
563 looking in the hashref for a key by that name, or trying to call that
564 method on the object. This is similar to how TT3 will function.
566 =head2 SCALAR VIRTUAL METHODS AND FILTERS
568 The following is the list of builtin virtual methods and filters
569 that can be called on scalar data types. In CET and TT3, filters and
570 virtual methods are more closely related. In general anywhere a
571 virtual method can be used a filter can be used also - and vice versa
572 - all scalar virtual methods can be used as filters.
574 In addition to the filters listed below, CET will automatically load
575 Template::Filters and use them if Template::Toolkit is installed.
577 In addition to the scalar virtual methods, any scalar will be
578 automatically converted to a single item list if a list virtual method
585 [% item.chunk(60).join("\n") %] Split string up into a list of chunks of text 60 chars wide.
589 [% item.collapse %] Strip leading and trailing whitespace and collapse all other space to one space.
593 [% item.defined %] Always true - because the undef sub translates all undefs to ''.
597 [% item.indent(3) %] Indent that number of spaces.
599 [% item.indent("Foo: ") %] Add the string "Foo: " to the beginning of every line.
603 [% item.eval %] Process the string as though it was a template. This will start the parsing
604 engine and will use the same configuration as the current process. CET is several times
605 faster at doing this than TT is and is considered acceptable.
609 Same as the eval filter.
613 Same as the redirect filter.
617 [% item.format('%d') %] Print the string out in the specified format. Each line is
618 processed separately.
622 [% item.hash %] Returns a one item hash with a key of "value" and a value of the item.
626 [% item.html %] Performs a very basic html encoding (swaps out &, <, > and " for the html entities)
630 [% item.lcfirst %] Capitalize the leading letter.
634 [% item.length %] Return the length of the string.
638 [% item.lower %] Return a lower-casified string.
642 [% item.match("(\w+) (\w+)") %] Return a list of items matching the pattern.
644 [% item.match("(\w+) (\w+)", 1) %] Same as before - but match globally.
648 [% item.null %] Do nothing.
652 [% item.remove("\s+") %] Same as remove - but is global and replaces with nothing.
656 [% item.redirect("output_file.html") %] - Writes the contents out to the specified file. The filename
657 must be relative to the OUTPUT_PATH configuration variable and the OUTPUT_PATH variable must be set.
661 [% item.repeat(3) %] Repeat the item 3 times
663 [% item.repeat(3, ' | ') %] Repeat the item 3 times separated with ' | '
667 [% item.replace("\s+", " ") %] Globally replace all space with
669 [% item.replace("foo", "bar", 0) Replace the first instance of foo with bar.
671 [% item.replace("(\w+)", "($1)") %] Surround all words with parenthesis.
675 [% item.search("(\w+)" %] Tests if the given pattern is in the string.
679 [% item.size %] Always returns 1.
681 =item split => \&vmethod_split,
683 [% item.split %] Returns an arrayref from the item split on " "
685 [% item.split("\s+") %] Returns an arrayref from the item split on /\s+/
687 [% item.split("\s+", 3) %] Returns an arrayref from the item split on /\s+/ splitting until 3 elements are found.
691 [% item.stderr %] Print the item to the current STDERR handle.
695 [% item.substr(i) %] Returns a substring of item starting at i and going to the end of the string.
697 [% item.substr(i, n) %] Returns a substring of item starting at i and going n characters.
701 [% item.trim %] Strips leading and trailing whitespace.
705 [% item.ucfirst %] Lower-case the leading letter.
709 [% item.upper %] Return a upper-casified string.
713 [% item.uri %] Perform a very basic URI encoding.
717 =head2 LIST VIRTUAL METHODS
721 The following methods can be called on an arrayref type data structures (scalar
722 types will automatically promote to a single element list and call these methods
727 [% mylist.first(3) %] Returns a list of the first 3 items in the list.
731 [% mylist.grep("^\w+\.\w+$") %] Returns a list of all items matching the pattern.
735 [% mylist.hash %] Returns a hashref with the array indexes as keys and the values as values.
739 [% mylist.join %] Joins on space.
740 [% mylist.join(", ") Joins on the passed argument.
744 [% mylist.last(3) %] Returns a list of the last 3 items in the list.
748 [% mylist.list %] Returns a reference to the list.
752 [% mylist.max %] Returns the last item in the array.
756 [% mylist.merge(list2) %] Returns a new list with all defined items from list2 added.
760 [% mylist.nsort %] Returns the numerically sorted items of the list. If the items are
761 hashrefs, a key containing the field to sort on can be passed.
765 [% mylist.pop %] Removes and returns the last element from the arrayref (the stash is modified).
769 [% mylist.push(23) %] Adds an element to the end of the arrayref (the stash is modified).
773 [% mylist.reverse %] Returns the list in reverse order.
777 [% mylist.shift %] Removes and returns the first element of the arrayref (the stash is modified).
781 [% mylist.size %] Returns the number of elements in the array.
785 [% mylist.slice(i, n) %] Returns a list from the arrayref beginning at index i and continuing for n items.
789 [% mylist.sort %] Returns the alphabetically sorted items of the list. If the items are
790 hashrefs, a key containing the field to sort on can be passed.
794 [% mylist.splice(i, n) %] Removes items from array beginning at i and continuing for n items.
796 [% mylist.splice(i, n, list2) %] Same as before, but replaces removed items with the items
801 [% mylist.unique %] Return a list of the unique items in the array.
805 [% mylist.unshift(23) %] Adds an item to the beginning of the arrayref.
809 =head2 HASH VIRTUAL METHODS
811 The following methods can be called on hash type data structures:
817 [% myhash.defined('a') %] Checks if a is defined in the hash.
821 [% myhash.delete('a') %] Deletes the item from the hash.
825 [% myhash.each.join(", ") %] Turns the contents of the hash into a list - subject
826 to change as TT is changing the operations of each and list.
830 [% myhash.exists('a') %] Checks if a is in the hash.
834 [% myhash.hash %] Returns a reference to the hash.
838 [% myhash.import(hash2) %] Overlays the keys of hash2 over the keys of myhash.
842 [% myhash.keys.join(', ') %] Returns an arrayref of the keys of the hash.
846 [% myhash.list %] Returns an arrayref with the hash as a single value (subject to change).
850 [% myhash.pairs %] Returns an arrayref of hashrefs where each hash contains {key => $key, value => $value}
851 for each value of the hash.
855 [% myhash.nsort.join(", ") %] Returns a numerically sorted list of the keys.
859 [% myhash.size %] Returns the number of key/value pairs in the hash.
863 [% myhash.sort.join(", ") Returns an alphabetically sorted list.
867 [% myhash.values.join(', ') %] Returns an arrayref of the values of the hash.
873 This section contains the alphabetical list of DIRECTIVES available
874 in the TT language. DIRECTIVES are the "functions" and control
875 structures that implement the Template Toolkit mini-language. For
876 further discussion and examples, please refer to the TT directives
884 Saves a block of text under a name for later use in PROCESS, INCLUDE,
885 and WRAPPER directives. Blocks may be placed anywhere within the
886 template being processed including after where they are used.
888 [% BLOCK foo %]Some text[% END %]
896 [% BLOCK foo %]Some text[% END %]
902 Anonymous BLOCKS can be used for capturing.
904 [% a = BLOCK %]Some text[% END %][% a %]
910 Anonymous BLOCKS can be used with macros.
915 Alias for LAST. Used for exiting FOREACH and WHILE loops.
919 Calls the variable (and any underlying coderefs) as in the GET method, but
920 always returns an empty string.
924 Used with the SWITCH directive. See the L</"SWITCH"> directive.
928 Used with the TRY directive. See the L</"TRY"> directive.
932 Clears any of the content currently generated in the innermost block
933 or template. This can be useful when used in conjunction with the TRY
934 statement to clear generated content if an error occurs later.
938 Used to reset the DEBUG_FORMAT configuration variable, or to turn
939 DEBUG statements on or off. This only has effect if the DEBUG_DIRS or
940 DEBUG_ALL flags were passed to the DEBUG configuration variable.
942 [% DEBUG format '($file) (line $line) ($text)' %]
948 Similar to SET, but only sets the value if a previous value was not
949 defined or was zero length.
951 [% DEFAULT foo = 'bar' %][% foo %] => 'bar'
953 [% foo = 'baz' %][% DEFAULT foo = 'bar' %][% foo %] => 'baz'
957 This is not provided in TT. DUMP inserts a Data::Dumper printout
958 of the variable or expression. If no argument is passed it will
959 dump the entire contents of the current variable stash (with
960 private keys removed.
962 If the template is being processed in a web request, DUMP will html
963 encode the DUMP automatically.
965 [% DUMP %] # dumps everything
971 Used with the IF directive. See the L</"IF"> directive.
975 Used with the IF directive. See the L</"IF"> directive.
979 Used to end a block directive.
983 Used to apply different treatments to blocks of text. It may operate as a BLOCK
984 directive or as a post operative directive. CET supports all of the filters in
985 Template::Filters. The lines between scalar virtual methods and filters is blurred (or
986 non-existent) in CET. Anything that is a scalar virtual method may be used as a FILTER.
988 TODO - enumerate the at least 7 ways to pass and use filters.
992 Alias for the FILTER directive. Note that | is similar to the
993 '.' in CGI::Ex::Template. Therefore a pipe cannot be used directly after a
994 variable name in some situations (the pipe will act only on that variable).
995 This is the behavior employed by TT3.
999 Used with the TRY directive. See the L</"TRY"> directive.
1007 Allows for iterating over the contents of any arrayref. If the variable is not an
1008 arrayref, it is automatically promoted to one.
1010 [% FOREACH i IN [1 .. 3] %]
1011 The variable i = [% i %]
1015 [% FOREACH j IN a %]
1016 The variable j = [% j %]
1029 You can also use the "=" instead of "IN" or "in".
1031 [% FOREACH i = [1 .. 3] %]
1032 The variable i = [% i %]
1037 Setting into a variable is optional.
1040 [% FOREACH a %] Hi [% END %]
1046 If the item being iterated is a hashref and the FOREACH does not
1047 set into a variable, then values of the hashref are copied into
1050 [% FOREACH [{a => 1}, {a => 2}] %]
1059 The FOREACH process uses the CGI::Ex::Template::Iterator class to handle
1060 iterations (It is compatible with Template::Iterator). During the FOREACH
1061 loop an object blessed into the iterator class is stored in the variable "loop".
1063 The loop variable provides the following information during a FOREACH:
1065 index - the current index
1066 max - the max index of the list
1067 size - the number of items in the list
1070 first - true if on the first item
1071 last - true if on the last item
1072 next - return the next item in the list
1073 prev - return the previous item in the list
1077 [% FOREACH [1 .. 3] %] [% loop.count %]/[% loop.size %] [% END %]
1083 The iterator is also available using a plugin. This allows for access
1084 to multiple "loop" variables in a nested FOREACH directive.
1086 [%~ USE outer_loop = Iterator(["a", "b"]) %]
1087 [%~ FOREACH i = outer_loop %]
1088 [%~ FOREACH j = ["X", "Y"] %]
1089 [% outer_loop.count %]-[% loop.count %] = ([% i %] and [% j %])
1100 FOREACH may also be used as a post operative directive.
1102 [% "$i" FOREACH i = [1 .. 5] %] => 12345
1106 Return the value of a variable or expression.
1110 The GET keyword may be omitted.
1114 [% 7 + 2 - 3 %] => 6
1116 See the section on VARIABLES.
1118 =item C<IF (IF / ELSIF / ELSE)>
1120 Allows for conditional testing. Expects an expression as its only
1121 argument. If the expression is true, the contents of its block are
1122 processed. If false, the processor looks for an ELSIF block. If an
1123 ELSIF's expression is true then it is processed. Finally it looks for
1124 an ELSE block which is processed if none of the IF or ELSIF's
1125 expressions were true.
1127 [% IF a == b %]A equaled B[% END %]
1131 [%- ELSIF a == c -%]
1134 Couldn't determine that A equaled anything.
1137 IF may also be used as a post operative directive.
1139 [% 'A equaled B' IF a == b %]
1143 Parse the contents of a file or block and insert them. Variables defined
1144 or modifications made to existing variables are discarded after
1145 a template is included.
1147 [% INCLUDE path/to/template.html %]
1149 [% INCLUDE "path/to/template.html" %]
1151 [% file = "path/to/template.html" %]
1154 [% BLOCK foo %]This is foo[% END %]
1157 Arguments may also be passed to the template:
1159 [% INCLUDE "path/to/template.html" a = "An arg" b = "Another arg" %]
1161 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1162 or RELATIVE configuration items are set.
1166 Insert the contents of a file without template parsing.
1168 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1169 or RELATIVE configuration items are set.
1173 Used to exit out of a WHILE or FOREACH loop.
1177 Takes a directive and turns it into a variable that can take arguments.
1179 [% MACRO foo(i, j) BLOCK %]You passed me [% i %] and [% j %].[% END %]
1181 [%~ foo("a", "b") %]
1186 You passed me a and b.
1187 You passed me 1 and 2.
1191 [% MACRO bar(max) FOREACH i = [1 .. max] %]([% i %])[% END %]
1201 Used to define variables that will be available via either the
1202 template or component namespace.
1204 Once defined, they cannot be overwritten.
1206 [% template.foobar %]
1207 [%~ META foobar = 'baz' %]
1208 [%~ META foobar = 'bing' %]
1216 Used to go to the next iteration of a WHILE or FOREACH loop.
1220 Only available if the EVAL_PERL configuration item is true (default is false).
1222 Allow eval'ing the block of text as perl. The block will be parsed and then eval'ed.
1227 print "The variable \$a was \"$a\"";
1228 $stash->set('b', "FooBar");
1234 The variable $a was "BimBam"
1237 During execution, anything printed to STDOUT will be inserted into the template. Also,
1238 the $stash and $context variables are set and are references to objects that mimic the
1239 interface provided by Template::Context and Template::Stash. These are provided for
1240 compatibility only. $self contains the current CGI::Ex::Template object.
1244 Parse the contents of a file or block and insert them. Unlike INCLUDE,
1245 no variable localization happens so variables defined or modifications made
1246 to existing variables remain after the template is processed.
1248 [% PROCESS path/to/template.html %]
1250 [% PROCESS "path/to/template.html" %]
1252 [% file = "path/to/template.html" %]
1255 [% BLOCK foo %]This is foo[% END %]
1258 Arguments may also be passed to the template:
1260 [% PROCESS "path/to/template.html" a = "An arg" b = "Another arg" %]
1262 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1263 or RELATIVE configuration items are set.
1267 Only available if the EVAL_PERL configuration item is true (default is false).
1268 Similar to the PERL directive, but you will need to append
1269 to the $output variable rather than just calling PRINT.
1273 Used to exit the innermost block or template and continue processing
1274 in the surrounding block or template.
1278 Used to set variables.
1280 [% SET a = 1 %][% a %] => "1"
1281 [% a = 1 %][% a %] => "1"
1282 [% b = 1 %][% SET a = b %][% a %] => "1"
1283 [% a = 1 %][% SET a %][% a %] => ""
1284 [% SET a = [1, 2, 3] %][% a.1 %] => "2"
1285 [% SET a = {b => 'c'} %][% a.b %] => "c"
1289 Used to exit the entire process method (out of all blocks and templates).
1290 No content will be processed beyond this point.
1294 Allow for SWITCH and CASE functionality.
1299 [% CASE "foo" %]a was foo
1300 [% CASE b %]a was bar
1301 [% CASE ["hi", "hello"] %]You said hi or hello
1302 [% CASE DEFAULT %]I don't know what you said
1307 You said hi or hello
1311 Change the type of enclosing braces used to delineate template tags. This
1312 remains in effect until the end of the enclosing block or template or until
1313 the next TAGS directive. Either a named set of tags must be supplied, or
1314 two tags themselves must be supplied.
1320 The named tags are (duplicated from TT):
1322 template => ['[%', '%]'], # default
1323 metatext => ['%%', '%%'], # Text::MetaText
1324 star => ['[*', '*]'], # TT alternate
1325 php => ['<?', '?>'], # PHP
1326 asp => ['<%', '%>'], # ASP
1327 mason => ['<%', '>' ], # HTML::Mason
1328 html => ['<!--', '-->'], # HTML comments
1332 Allows for throwing an exception. If the exception is not caught
1333 via the TRY DIRECTIVE, the template will abort processing of the directive.
1335 [% THROW mytypes.sometime 'Something happened' arg1 => val1 %]
1337 See the TRY directive for examples of usage.
1341 The TRY block directive will catch exceptions that are thrown
1342 while processing its block (It cannot catch parse errors unless
1343 they are in included files or evaltt'ed strings. The TRY block
1344 will then look for a CATCH block that will be processed. While
1345 it is being processed, the "error" variable will be set with the thrown
1346 exception as the value. After the TRY block - the FINAL
1347 block will be ran whether or not an error was thrown (unless a CATCH
1348 block throws an error).
1350 Note: Parse errors cannot be caught unless they are in an eval FILTER, or are
1351 in a separate template being INCLUDEd or PROCESSed.
1354 Nothing bad happened.
1358 This section runs no matter what happens.
1363 Nothing bad happened.
1364 This section runs no matter what happens.
1369 [% THROW "Something happened" %]
1372 Error.type: [% error.type %]
1373 Error.info: [% error.info %]
1375 This section runs no matter what happens.
1380 Error: undef error - Something happened
1382 Error.info: Something happened
1383 This section runs no matter what happens.
1385 You can give the error a type and more information including named arguments.
1386 This information replaces the "info" property of the exception.
1389 [% THROW foo.bar "Something happened" "grrrr" foo => 'bar' %]
1392 Error.type: [% error.type %]
1393 Error.info: [% error.info %]
1394 Error.info.0: [% error.info.0 %]
1395 Error.info.1: [% error.info.1 %]
1396 Error.info.args.0: [% error.info.args.0 %]
1397 Error.info.foo: [% error.info.foo %]
1400 Would print something like:
1402 Error: foo.bar error - HASH(0x82a395c)
1404 Error.info: HASH(0x82a395c)
1405 Error.info.0: Something happened
1407 Error.info.args.0: Something happened
1410 You can also give the CATCH block a type to catch. And you
1411 can nest TRY blocks. If types are specified, CET will try and
1412 find the closest matching type. Also, an error object can
1413 be re-thrown using $error as the argument to THROW.
1417 [% THROW foo.bar "Something happened" %]
1421 Caught default - but rethrew.
1429 Caught anything else.
1434 Caught default - but rethrew.
1440 Same as IF but condition is negated.
1442 [% UNLESS 0 %]hi[% END %] => hi
1444 Can also be a post operative directive.
1448 Allows for loading a Template::Toolkit style plugin.
1450 [% USE iter = Iterator(['foo', 'bar']) %]
1451 [%~ iter.get_first %]
1459 Note that it is possible to send arguments to the new object
1460 constructor. It is also possible to omit the variable name being
1461 assigned. In that case the name of the plugin becomes the variable.
1463 [% USE Iterator(['foo', 'bar', 'baz']) %]
1464 [%~ Iterator.get_first %]
1472 Plugins that are loaded are looked up for in the namespace listed in
1473 the PLUGIN_BASE directive which defaults to Template::Plugin. So in
1474 the previous example, if Template::Toolkit was installed, the iter
1475 object would loaded by the class Template::Plugin::Iterator. In CET,
1476 an effective way to disable plugins is to set the PLUGIN_BASE to a
1477 non-existent base such as "_" (In TT it will still fall back to look
1478 in Template::Plugin).
1480 Note: The iterator plugin will fall back and use
1481 CGI::Ex::Template::Iterator if Template::Toolkit is not installed. No
1482 other plugins come installed with CGI::Ex::Template.
1484 The names of the Plugin being loaded from PLUGIN_BASE are case
1485 insensitive. However, using case insensitive names is bad as it
1486 requires scanning the @INC directories for any module matching the
1487 PLUGIN_BASE and caching the result (OK - not that bad).
1489 If the plugin is not found and the LOAD_PERL directive is set, then
1490 CET will try and load a module by that name (note: this type of lookup
1491 is case sensitive and will not scan the @INC dirs for a matching
1494 # The LOAD_PERL directive should be set to 1
1495 [% USE cet = CGI::Ex::Template %]
1496 [%~ cet.dump_parse('2 * 3').replace('\s+', ' ') %]
1500 $VAR1 = [ \[ '*', '2', '3' ], 0 ];
1502 See the PLUGIN_BASE, and PLUGINS configuration items.
1504 See the documentation for Template::Manual::Plugins.
1508 Will process a block of code while a condition is true.
1524 [% WHILE (i = i - 1) %]
1534 Note that (f = f - 1) is a valid expression that returns the value
1535 of the assignment. The parenthesis are not optional.
1537 WHILE has a built in limit of 1000 iterations. This is controlled by the
1538 global variable $WHILE_MAX in CGI::Ex::Template.
1540 WHILE may also be used as a post operative directive.
1542 [% "$i" WHILE (i = i + 1) < 7 %] => 123456
1546 Block directive. Processes contents of its block and then passes them
1547 in the [% content %] variable to the block or filename listed in the
1551 My content to be processed.[% a = 2 %]
1563 My content to be processed.
1566 The WRAPPER directive may also be used as a post directive.
1568 [% BLOCK baz %]([% content %])[% END -%]
1569 [% "foobar" WRAPPER baz %]
1581 The following operators are available in CGI::Ex::Template. Except
1582 where noted these are the same operators available in TT. They are
1583 listed in the order of their precedence (the higher the precedence the
1590 Binary. The dot operator. Allows for accessing sub-members, methods, or
1591 virtual methods of nested data structures.
1593 my $obj->process(\$content, {a => {b => [0, {c => [34, 57]}]}}, \$output);
1595 [% a.b.1.c.0 %] => 34
1597 Note: on access to hashrefs, any hash keys that match the sub key name
1598 will be used before a virtual method of the same name. For example if
1599 a passed hash contained pair with a keyname "defined" and a value of
1600 "2", then any calls to hash.defined(another_keyname) would always
1601 return 2 rather than using the vmethod named "defined." To get around
1602 this limitation use the "|" operator (listed next). Also - on objects
1603 the "." will always try and call the method by that name. To always
1604 call the vmethod - use "|".
1608 Binary. The pipe operator. Similar to the dot operator. Allows for
1609 explicit calling of virtual methods and filters (filters are "merged"
1610 with virtual methods in CGI::Ex::Template and TT3) when accessing
1611 hashrefs and objects. See the note for the "." operator.
1613 The pipe character is similar to TT2 in that it can be used in place
1614 of a directive as an alias for FILTER. It similar to TT3 in that it
1615 can be used for virtual method access. This duality is one source of
1616 difference between CGI::Ex::Template and TT2 compatibility. Templates
1617 that have directives that end with a variable name that then use the
1618 "|" directive to apply a filter will be broken as the "|" will be
1619 applied to the variable name.
1621 The following two cases will do the same thing.
1625 [% foo FILTER html %]
1627 Though they do the same thing, internally, foo|html is stored as a
1628 single variable while "foo FILTER html" is stored as the variable foo
1629 which is then passed to the FILTER html.
1631 A TT2 sample that would break in CGI::Ex::Template or TT3 is:
1633 [% PROCESS foo a = b | html %]
1635 Under TT2 the content returned by "PROCESS foo a = b" would all be
1636 passed to the html filter. Under CGI::Ex::Template and TT3, b would
1637 be passed to the html filter before assigning it to the variable "a"
1638 before the template foo was processed.
1640 A simple fix is to do any of the following:
1642 [% PROCESS foo a = b FILTER html %]
1644 [% | html %][% PROCESS foo a = b %][% END %]
1646 [% FILTER html %][% PROCESS foo a = b %][% END %]
1648 This shouldn't be too much hardship and offers the great return of disambiguating
1649 virtual method access.
1653 Binary. X raised to the Y power. This isn't available in TT 2.15.
1659 Unary not. Negation of the value.
1661 =item C<- unary_minus>
1663 Unary minus. Returns the value multiplied by -1. The operator
1664 "unary_minus" is used internally by CGI::Ex::Template to provide for -
1665 to be listed in the precedence table twice.
1667 [% a = 1 ; b = -a ; b %] => -1
1671 Binary. Multiplication.
1675 Binary. Division. Note that / is floating point division, but div and
1676 DIV are integer division.
1697 Binary. String concatenation.
1699 [% "a" ~ "b" %] => ab
1701 =item C<< < > <= >= >>
1703 Binary. Numerical comparators.
1705 =item C<lt gt le ge>
1707 Binary. String comparators.
1711 Binary. Equality test. TT chose to use Perl's eq for both operators.
1712 There is no test for numeric equality.
1716 Binary. Non-equality test. TT chose to use Perl's ne for both
1717 operators. There is no test for numeric non-equality.
1721 Multiple arity. And. All values must be true. If all values are true, the last
1722 value is returned as the truth value.
1724 [% 2 && 3 && 4 %] => 4
1728 Multiple arity. Or. The first true value is returned.
1730 [% 0 || '' || 7 %] => 7
1734 Binary. Range creator. Returns an arrayref containing the values
1735 between and including the first and last arguments.
1737 [% t = [1 .. 5] %] => variable t contains an array with 1,2,3,4, and 5
1739 It is possible to place multiple ranges in the same [] constructor. This is not available in TT.
1741 [% t = [1..3, 6..8] %] => variable t contains an array with 1,2,3,6,7,8
1743 The .. operator is the only operator that returns a list of items.
1747 Trinary. Can be nested with other ?: pairs.
1749 [% 1 ? 2 : 3 %] => 2
1750 [% 0 ? 2 : 3 %] => 3
1754 Assignment. Sets the left-hand side to the value of the righthand side. In order
1755 to not conflict with SET, FOREACH and other operations, this operator is only
1756 available in parenthesis. Returns the value of the righthand side.
1758 [% (a = 1) %] --- [% a %] => 1 --- 1
1762 Lower precedence version of the '!' operator.
1766 Lower precedence version of the '&&' operator.
1770 Lower precedence version of the '||' operator.
1774 Multiple arity. This operator is not used in TT. It is used internally
1775 by CGI::Ex::Template to delay the creation of a hash until the
1776 execution of the compiled template.
1780 Multiple arity. This operator is not used in TT. It is used internally
1781 by CGI::Ex::Template to delay the creation of an array until the
1782 execution of the compiled template.
1789 Chomping refers to the handling of whitespace immediately before and
1790 immediately after template tags. By default, nothing happens to this
1791 whitespace. Modifiers can be placed just inside the opening and just
1792 before the closing tags to control this behavior.
1794 Additionally, the PRE_CHOMP and POST_CHOMP configuration variables can
1795 be set and will globally control all chomping behavior for tags that
1796 do not have their own chomp modifier. PRE_CHOMP and POST_CHOMP can
1797 be set to any of the following values:
1799 none: 0 + Template::Constants::CHOMP_NONE
1800 one: 1 - Template::Constants::CHOMP_ONE
1801 collapse: 2 = Template::Constants::CHOMP_COLLAPSE
1802 greedy: 3 ~ Template::Constants::CHOMP_GREEDY
1808 Don't do any chomping. The "+" sign is used to indicate CHOMP_NONE.
1824 =item CHOMP_ONE (formerly known as CHOMP_ALL)
1826 Delete any whitespace up to the adjacent newline. The "-" is used to indicate CHOMP_ONE.
1840 =item CHOMP_COLLAPSE
1842 Collapse adjacent whitespace to a single space. The "=" is used to indicate CHOMP_COLLAPSE.
1856 Remove all adjacent whitespace. The "~" is used to indicate CHOMP_GREEDY.
1868 =head1 CONFIGURATION
1870 The following TT2 configuration variables are supported (in
1871 alphabetical order). Note: for further discussion you can refer to
1872 the TT config documentation.
1874 These variables should be passed to the "new" constructor.
1876 my $obj = CGI::Ex::Template->new(
1877 VARIABLES => \%hash_of_variables,
1889 Boolean. Default false. Are absolute paths allowed for included files.
1893 Boolean. Default 1. Clear blocks that were set during the process method.
1897 A hashref of blocks that can be used by the process method.
1900 block_1 => sub { ... }, # coderef that returns a block
1901 block_2 => 'A String', # simple string
1904 Note that a Template::Document cannot be supplied as a value (TT
1905 supports this). However, it is possible to supply a value that is
1906 equal to the hashref returned by the load_parsed_tree method.
1910 Number of compiled templates to keep in memory. Default undef.
1911 Undefined means to allow all templates to cache. A value of 0 will
1912 force no caching. The cache mechanism will clear templates that have
1913 not been used recently.
1917 Base directory to store compiled templates. Default undef. Compiled
1918 templates will only be stored if one of COMPILE_DIR and COMPILE_EXT is
1923 Extension to add to stored compiled template filenames. Default undef.
1927 Hashref. Used to define variables that will be "folded" into the
1928 compiled template. Variables defined here cannot be overridden.
1930 CONSTANTS => {my_constant => 42},
1932 A template containing:
1934 [% constants.my_constant %]
1936 Will have the value 42 compiled in.
1938 Constants defined in this way can be chained as in [%
1939 constant.foo.bar.baz %] but may only interpolate values that are set
1940 before the compile process begins. This goes one step beyond TT in
1941 that any variable set in VARIABLES, or PRE_DEFINE, or passed to the
1942 process method are allowed - they are not in TT. Variables defined in
1943 the template are not available during the compile process.
1961 [% constants.foo.${constants.bang} %]
1963 Will correctly print 57.
1965 GOOD (non-tt behavior)
1967 [% constants.foo.$bam.${constants.bing} %]
1969 CGI::Ex::Template will print 42 because the value of bam is
1970 known at compile time. TT would print '' because the value of $bam
1971 is not yet defined in the TT engine.
1977 [% bam = 'somethingelse' %]
1978 [% constants.foo.$bam.${constants.bing} %]
1980 Will still print 42 because the value of bam used comes from
1981 variables defined before the template was compiled. TT will still print ''.
1983 =item CONSTANT_NAMESPACE
1985 Allow for setting the top level of values passed in CONSTANTS. Default
1986 value is 'constants'.
1990 Takes a list of constants |'ed together which enables different
1991 debugging modes. Alternately the lowercase names may be used (multiple
1992 values joined by a ",".
1994 The only supported TT values are:
1995 DEBUG_UNDEF (2) - debug when an undefined value is used.
1996 DEBUG_DIRS (8) - debug when a directive is used.
1997 DEBUG_ALL (2047) - turn on all debugging.
1999 Either of the following would turn on undef and directive debugging:
2001 DEBUG => 'undef, dirs', # preferred
2003 DEBUG => DEBUG_UNDEF | DEBUG_DIRS, # constants from Template::Constants
2007 Change the format of messages inserted when DEBUG has DEBUG_DIRS set on.
2008 This essentially the same thing as setting the format using the DEBUG
2013 The name of a default template file to use if the passed on is not found.
2017 String to use to split INCLUDE_PATH with. Default is :. It is more
2018 straight forward to just send INCLUDE_PATH an arrayref of paths.
2022 Set a string to use as the closing delimiter for TT. Default is "%]".
2026 Boolean. Default false. If set to a true value, PERL and RAWPERL blocks
2027 will be allowed to run. This is a potential security hole, as arbitrary
2028 perl can be included in the template. If Template::Toolkit is installed,
2029 a true EVAL_PERL value also allows the perl and evalperl filters to be used.
2033 Allow for passing in TT style filters.
2036 filter1 => sub { my $str = shift; $s =~ s/./1/gs; $s },
2037 filter2 => [sub { my $str = shift; $s =~ s/./2/gs; $s }, 0],
2038 filter3 => [sub { my ($context, @args) = @_; return sub { my $s = shift; $s =~ s/./3/gs; $s } }, 1],
2043 1([% a | filter1 %])
2044 2([% a | filter2 %])
2045 3([% a | filter3 %])
2048 my $obj = CGI::Ex::Template->new(FILTERS => $filters);
2049 $obj->process(\$str) || die $obj->error;
2057 Filters passed in as an arrayref should contain a coderef and a value
2058 indicating if they are dynamic or static (true meaning dynamic). The
2059 dynamic filters are passed the pseudo context object and any arguments
2060 and should return a coderef that will be called as the filter. The filter
2061 coderef is then passed the string.
2065 A string or an arrayref or coderef that returns an arrayref that
2066 contains directories to look for files included by processed
2071 Non-TT item. Same as INCLUDE_PATH but only takes an arrayref. If not specified
2072 then INCLUDE_PATH is turned into an arrayref and stored in INCLUDE_PATHS.
2073 Overrides INCLUDE_PATH.
2077 Boolean. Specifies whether variables in text portions of the template will be
2078 interpolated. For example, the $variable and ${var.value} would be substituted
2079 with the appropriate values from the variable cache (if INTERPOLATE is on).
2081 [% IF 1 %]The variable $variable had a value ${var.value}[% END %]
2086 Indicates if the USE directive can fall back and try and load a perl module
2087 if the indicated module was not found in the PLUGIN_BASE path. See the
2092 No Template::Namespace::Constants support. Hashref of hashrefs representing
2093 constants that will be folded into the template at compile time.
2095 CGI::Ex::Template->new(NAMESPACE => {constants => {
2101 CGI::Ex::Template->new(CONSTANTS => {
2105 Any number of hashes can be added to the NAMESPACE hash.
2109 Alternate way of passing in the output location for processed templates.
2110 If process is not passed an output argument, it will look for this value.
2112 See the process method for a listing of possible values.
2116 Base path for files written out via the process method or via the redirect
2117 and file filters. See the redirect virtual method and the process method
2118 for more information.
2122 A hashref of mappings of plugin modules.
2125 Iterator => 'Template::Plugin::Iterator',
2129 See the USE directive for more information.
2133 Default value is Template::Plugin. The base module namespace
2134 that template plugins will be looked for. See the USE directive
2135 for more information.
2139 Set the type of chomping at the ending of a tag.
2140 See the section on chomping for more information.
2144 A list of templates to be processed and appended to the content
2145 after the main template. During this processing the "template"
2146 namespace will contain the name of the main file being processed.
2148 This is useful for adding a global footer to all templates.
2152 Set the type of chomping at the beginning of a tag.
2153 See the section on chomping for more information.
2157 Same as the VARIABLES configuration item.
2161 A list of templates to be processed before and pre-pended to the content
2162 before the main template. During this processing the "template"
2163 namespace will contain the name of the main file being processed.
2165 This is useful for adding a global header to all templates.
2169 Specify a file to use as the template rather than the one passed in
2170 to the ->process method.
2174 Boolean. Default false. Indicates that INCLUDED or PROCESSED files
2175 can refer to each other in a circular manner. Be careful about recursion.
2179 Boolean. Default false. If true, allows filenames to be specified
2180 that are relative to the currently running process.
2184 Set a string to use as the opening delimiter for TT. Default is "[%".
2188 Allow for setting the type of tag delimiters to use for parsing the TT.
2189 See the TAGS directive for a listing of the available types.
2193 Remove leading and trailing whitespace from blocks and templates.
2194 This operation is performed after all enclosed template tags have
2199 This is not a TT configuration option. This option expects to be a code
2200 ref that will be called if a variable is undefined during a call to get_variable.
2201 It is passed the variable identity array as a single argument. This
2202 is most similar to the "undefined" method of Template::Stash. It allows
2203 for the "auto-defining" of a variable for use in the template. It is
2204 suggested that UNDEFINED_GET be used instead as UNDEFINED_ANY is a little
2205 to general in defining variables.
2207 You can also sub class the module and override the undefined_any method.
2211 This is not a TT configuration option. This option expects to be a code
2212 ref that will be called if a variable is undefined during a call to GET.
2213 It is passed the variable identity array as a single argument. This is more useful
2214 than UNDEFINED_ANY in that it is only called during a GET directive
2215 rather than in embedded expressions (such as [% a || b || c %]).
2217 You can also sub class the module and override the undefined_get method.
2221 A hashref of variables to initialize the template stash with. These
2222 variables are available for use in any of the executed templates.
2223 See the section on VARIABLES for the types of information that can be passed in.
2229 =head1 UNSUPPORTED TT CONFIGURATION
2235 This will not be supported. You will have to use the full case directive names.
2236 (It was in the beta code but was removed prior to release).
2240 This will be supported - just not done yet.
2244 This will be supported - just not done yet.
2248 This will not be supported.
2250 =item LOAD_TEMPLATES
2252 CGI::Ex::Template has its own mechanism for loading and storing
2253 compiled templates. TT would use a Template::Provider that would
2254 return a Template::Document. The closest thing in CGI::Ex::Template
2255 is the load_parsed_template method. There is no immediate plan to
2256 support the TT behavior.
2260 CGI::Ex::Template uses its own mechanism for loading plugins. TT
2261 would use a Template::Plugins object to load plugins requested via the
2262 USE directive. The functionality for doing this in CGI::Ex::Template
2263 is contained in the list_plugins method and the play_USE method. There
2264 is no immediate plan to support the TT behavior.
2266 Full support is offered for the PLUGINS and LOAD_PERL configuration items.
2268 Also note that CGI::Ex::Template only natively supports the Iterator plugin.
2269 Any of the other plugins requested will need to provided by installing
2270 Template::Toolkit or the appropriate plugin module.
2274 CGI::Ex::Template uses its own mechanism for loading filters. TT
2275 would use the Template::Filters object to load filters requested via the
2276 FILTER directive. The functionality for doing this in CGI::Ex::Template
2277 is contained in the list_filters method and the get_variable method.
2279 Full support is offered for the FILTERS configuration item.
2283 This option is used by the LOAD_TEMPLATES and LOAD_PLUGINS options and
2284 is not applicable in CGI::Ex::Template.
2288 CGI::Ex::Template has no concept of service (theoretically the CGI::Ex::Template
2293 CGI::Ex::Template provides its own pseudo context object to plugins,
2294 filters, and perl blocks. The CGI::Ex::Template model doesn't really
2295 allow for a separate context. CGI::Ex::Template IS the context.
2299 CGI::Ex::Template manages its own stash of variables. A pseudo stash
2300 object is available via the pseudo context object for use in plugins,
2301 filters, and perl blocks.
2305 CGI::Ex::Template has its own built in parser. The closest similarity is
2306 the parse_tree method. The output of parse_tree is an optree that is
2307 later run by execute_tree.
2311 CGI::Ex::Template maintains its own grammar. The grammar is defined
2312 in the parse_tree method and the callbacks listed in the global
2313 $DIRECTIVES hashref.
2318 =head1 VARIABLE PARSE TREE
2320 CGI::Ex::Template parses templates into an tree of operations. Even
2321 variable access is parsed into a tree. This is done in a manner
2322 somewhat similar to the way that TT operates except that nested
2323 variables such as foo.bar|baz contain the '.' or '|' in between each
2324 name level. Operators are parsed and stored as part of the variable (it
2325 may be more appropriate to say we are parsing a term or an expression).
2327 The following table shows a variable or expression and the corresponding parsed tree
2328 (this is what the parse_variable method would return).
2332 one.two [ 'one', 0, '.', 'two', 0 ]
2333 one|two [ 'one', 0, '|', 'two', 0 ]
2334 one.$two [ 'one', 0, '.', ['two', 0 ], 0 ]
2335 one(two) [ 'one', [ ['two', 0] ] ]
2336 one.${two().three} [ 'one', 0, '.', ['two', [], '.', 'three', 0], 0]
2339 "one"|length [ \"one", 0, '|', 'length', 0 ]
2340 "one $a two" [ \ [ '~', 'one ', ['a', 0], ' two' ], 0 ]
2341 [0, 1, 2] [ \ [ 'array', 0, 1, 2 ], 0 ]
2342 [0, 1, 2].size [ \ [ 'array', 0, 1, 2 ], 0, '.', 'size', 0 ]
2343 ['a', a, $a ] [ \ [ 'array', 'a', ['a', 0], [['a', 0], 0] ], 0]
2344 {a => 'b'} [ \ [ 'hash', 'a', 'b' ], 0 ]
2345 {a => 'b'}.size [ \ [ 'hash', 'a', 'b' ], 0, '.', 'size', 0 ]
2346 {$a => b} [ \ [ 'hash', ['a', 0], ['b', 0] ], 0 ]
2347 1 + 2 [ \ [ '+', 1, 2 ], 0]
2348 a + b [ \ [ '+', ['a', 0], ['b', 0] ], 0 ]
2349 a * (b + c) [ \ [ '*', ['a', 0], [ \ ['+', ['b', 0], ['c', 0]], 0 ]], 0 ]
2350 (a + b) [ \ [ '+', ['a', 0], ['b', 0] ]], 0 ]
2351 (a + b) * c [ \ [ '*', [ \ [ '+', ['a', 0], ['b', 0] ], 0 ], ['c', 0] ], 0 ]
2352 a ? b : c [ \ [ '?', ['a', 0], ['b', 0], ['c', 0] ], 0 ]
2353 a || b || c [ \ [ '||', ['a', 0], [ \ [ '||', ['b', 0], ['c', 0] ], 0 ] ], 0 ]
2354 ! a [ \ [ '!', ['a', 0] ], 0 ]
2356 Some notes on the parsing.
2358 Operators are parsed as part of the variable and become part of the variable tree.
2360 Operators are stored in the variable tree using a reference to the arrayref - which
2361 allows for quickly descending the parsed variable tree and determining that the next
2362 node is an operator.
2364 Parenthesis () can be used at any point in an expression to disambiguate precedence.
2366 "Variables" that appear to be literal strings or literal numbers
2367 are returned as the literal (no operator tree).
2369 The following perl can be typed at the command line to view the parsed variable tree:
2371 perl -e 'use CGI::Ex::Template; print CGI::Ex::Template::dump_parse("foo.bar + 2")."\n"'
2373 Also the following can be included in a template to view the output in a template:
2375 [% USE cet = CGI::Ex::Template %]
2376 [%~ cet.dump_parse('foo.bar + 2').replace('\s+', ' ') %]
2379 =head1 SEMI PUBLIC METHODS
2381 The following list of methods are other interesting methods of CET that
2382 may be re-implemented by subclasses of CET.
2388 This method allows for returning a Data::Dumper dump of a parsed variable. It is mainly used for testing.
2392 Creates an exception object blessed into the package listed in
2393 $CGI::Ex::Template::PACKAGE_EXCEPTION.
2395 =item C<execute_tree>
2397 Executes a parsed tree (returned from parse_tree)
2399 =item C<get_variable>
2401 Turns a variable identity array into the parsed variable. This
2402 method is also responsible for playing operators and running virtual methods
2403 and filters. The method could more accurately be called play_expression.
2405 =item C<include_filename>
2407 Takes a file path, and resolves it into the full filename using
2408 paths from INCLUDE_PATH or INCLUDE_PATHS.
2412 Resolves the file passed, and then returns its contents.
2414 =item C<list_filters>
2416 Dynamically loads the filters list from Template::Filters when a filter
2417 is used that is not natively implemented in CET.
2419 =item C<list_plugins>
2421 Returns an arrayref of modules that are under a base Namespace.
2423 my @modules = @{ $self->list_plugins({base => 'Template::Plugins'}) }:
2425 =item C<load_parsed_tree>
2427 Given a filename or a string reference will return a parsed document
2428 hash that contains the parsed tree.
2430 my $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");
2434 Allow for the multitudinous ways that TT parses arguments. This allows
2435 for positional as well as named arguments. Named arguments can be separated with a "=" or "=>",
2436 and positional arguments should be separated by " " or ",". This only returns an array
2437 of parsed variables. Use vivify_args to translate to the actual values.
2441 Used by load_parsed_tree. This is the main grammar engine of the program. It
2442 uses method in the $DIRECTIVES hashref to parse different DIRECTIVE TYPES.
2444 =item C<parse_variable>
2446 Used to parse a variable, an expression, a literal string, or a number. It
2447 returns a parsed variable tree. Samples of parsed variables can be found in the VARIABLE PARSE TREE
2450 =item C<set_variable>
2452 Used to set a variable. Expects a variable identity array and the value to set. It
2453 will autovifiy as necessary.
2457 Creates an exception object from the arguments and dies.
2459 =item C<undefined_any>
2461 Called during get_variable if a value is returned that is undefined. This could
2462 be used to magically create variables on the fly. This is similar to Template::Stash::undefined.
2463 It is suggested that undefined_get be used instead. Default behavior returns undef. You
2464 may also pass a coderef via the UNDEFINED_ANY configuration variable. Also, you can try using
2465 the DEBUG => 'undef', configuration option which will throw an error on undefined variables.
2467 =item C<undefined_get>
2469 Called when a variable is undefined during a GET directive. This is useful to
2470 see if a value that is about to get inserted into the text is undefined. undefined_any is a little
2471 too general for most cases. Also, you may pass a coderef via the UNDEFINED_GET configuration variable.
2473 =item C<vivify_args>
2475 Turns an arrayref of arg identities parsed by parse_args and turns
2476 them into the actual values.
2481 =head1 OTHER UTILITY METHODS
2483 The following is a brief list of other methods used by CET. Generally, these
2484 shouldn't be overwritten by subclasses.
2488 =item C<apply_precedence>
2490 Allows for parsed operator array to be translated to a tree based
2491 upon operator precedence.
2495 Used to create a "pseudo" context object that allows for portability
2496 of TT plugins, filters, and perl blocks that need a context object.
2500 TT2 Holdover that is used once for binmode setting during a TT2 test.
2504 Used to get debug info on a directive if DEBUG_DIRS is set.
2508 Methods by these names implement filters that are more than one line.
2510 =item C<get_line_number_by_index>
2512 Used to turn string index position into line number
2514 =item C<interpolate_node>
2516 Used for parsing text nodes for dollar variables when interpolate is on.
2520 Methods by these names are used by parse_tree to parse the template. These are the grammar.
2524 Methods by these names are used by execute_tree to execute the parsed tree.
2526 =item C<play_operator>
2528 Used to execute any found operators
2532 Called by process and the PROCESS, INCLUDE and other directives.
2536 Reads contents of passed filename - throws file exception on error.
2538 =item C<split_paths>
2540 Used to split INCLUDE_PATH or other directives if an arrayref is not passed.
2544 Return a reference to the current stash of variables. This is currently only used
2545 by the pseudo context object and may disappear at some point.
2549 Methods by these names implement virtual methods that are more than one line.
2553 Used to create a weak reference to self to avoid circular references. (this
2554 is needed by macros)
2561 Paul Seamons <paul at seamons dot com>