1Template::Alloy(3) User Contributed Perl Documentation Template::Alloy(3)
2
3
4
6 Template::Alloy - TT2/3, HT, HTE, Tmpl, and Velocity Engine
7
9 Template::Toolkit style usage
10
11 my $t = Template::Alloy->new(
12 INCLUDE_PATH => ['/path/to/templates'],
13 );
14
15 my $swap = {
16 key1 => 'val1',
17 key2 => 'val2',
18 code => sub { 42 },
19 hash => {a => 'b'},
20 };
21
22 # print to STDOUT
23 $t->process('my/template.tt', $swap)
24 ⎪⎪ die $t->error;
25
26 # process into a variable
27 my $out = '';
28 $t->process('my/template.tt', $swap, \$out);
29
30 ### Alloy uses the same syntax and configuration as Template::Toolkit
31
32 HTML::Template::Expr style usage
33
34 my $t = Template::Alloy->new(
35 filename => 'my/template.ht',
36 path => ['/path/to/templates'],
37 );
38
39 my $swap = {
40 key1 => 'val1',
41 key2 => 'val2',
42 code => sub { 42 },
43 hash => {a => 'b'},
44 };
45
46 $t->param($swap);
47
48 # print to STDOUT (errors die)
49 $t->output(print_to => \*STDOUT);
50
51 # process into a variable
52 my $out = $t->output;
53
54 ### Alloy can also use the same syntax and configuration as HTML::Template
55
56 Text::Tmpl style usage
57
58 my $t = Template::Alloy->new;
59
60 my $swap = {
61 key1 => 'val1',
62 key2 => 'val2',
63 code => sub { 42 },
64 hash => {a => 'b'},
65 };
66
67 $t->set_delimiters('#[', ']#');
68 $t->set_strip(0);
69 $t->set_values($swap);
70 $t->set_dir('/path/to/templates');
71
72 my $out = $t->parse_file('my/template.tmpl');
73
74 my $str = "Foo #[echo $key1]# Bar";
75 my $out = $t->parse_string($str);
76
77 ### Alloy uses the same syntax and configuration as Text::Tmpl
78
79 Velocity (VTL) style usage
80
81 my $t = Template::Alloy->new;
82
83 my $swap = {
84 key1 => 'val1',
85 key2 => 'val2',
86 code => sub { 42 },
87 hash => {a => 'b'},
88 };
89
90 my $out = $t->merge('my/template.vtl', $swap);
91
92 my $str = "#set($foo 1 + 3) ($foo) ($bar) ($!baz)";
93 my $out = $t->merge(\$str, $swap);
94
96 "An alloy is a homogeneous mixture of two or more elements"
97 (http://en.wikipedia.org/wiki/Alloy).
98
99 Template::Alloy represents the mixing of features and capabilities from
100 all of the major mini-language based template systems (support for non-
101 mini-language based systems will happen eventually). With Tem‐
102 plate::Alloy you can use your favorite template interface and syntax
103 and get features from each of the other major template systems. And
104 Template::Alloy is fast - whether your using mod_perl, cgi, or running
105 from the commandline. There is even Template::Alloy::XS for getting a
106 little more speed when that is necessary.
107
108 Template::Alloy happened by accident (accidentally on purpose). The
109 Template::Alloy (Alloy hereafter) was originally a part of the CGI::Ex
110 suite that performed simple variable interpolation. It used TT2 style
111 variables in TT2 style tags "[% foo.bar %]". That was all the original
112 Template::Alloy did. This was fine and dandy for a couple of years.
113 In winter of 2005-2006 Alloy was revamped to add a few features. One
114 thing led to another and soon Alloy provided for most of the features
115 of TT2 as well as some from TT3. Template::Alloy now provides a full-
116 featured implementation of the Template::Toolkit language.
117
118 After a move to a new company that was using HTML::Template::Expr and
119 Text::Tmpl templates, support was investigated and interfaces for
120 HTML::Template, HTML::Template::Expr, Text::Tmpl, and Velocity (VTL)
121 were added. All of the various engines offer the same features - just
122 using different syntaxes and interfaces.
123
124 Template::Toolkit brought the most to the table. HTML::Template
125 brought the LOOP directive. HTML::Template::Expr brough more vmethods
126 and using vmethods as top level functions. Text::Tmpl brought the COM‐
127 MENT directive and encouraged speed matching (Text::Tmpl is almost
128 entirely C based and is very fast). The Velocity engine brought
129 AUTO_EVAL and SHOW_UNDEFINED_INTERP.
130
131 Most of the standard Template::Toolkit documentation covering direc‐
132 tives, variables, configuration, plugins, filters, syntax, and vmethods
133 should apply to Alloy just fine (This pod tries to explain everything -
134 but there is too much). See Template::Alloy::TT for a listing of the
135 differences between Alloy and TT.
136
137 Most of the standard HTML::Template and HTML::Template::Expr documenta‐
138 tion covering methods, variables, expressions, and syntax will apply to
139 Alloy just fine as well.
140
141 Most of the standard Text::Tmpl documentation applies, as does the doc‐
142 umentation covering Velocity (VTL).
143
144 So should you use Template::Alloy ? Well, try it out. It may give you
145 no visible improvement. Or it could.
146
148 Template::Alloy uses a recursive regex based grammar (early versions
149 during the CGI::Ex::Template phase did not). This allows for the
150 embedding of opening and closing tags inside other tags (as in [% a =
151 "[% 1 + 2 %]" ; a⎪eval %]). The individual methods such as parse_expr
152 and play_expr may be used by external applications to add TT style
153 variable parsing to other applications.
154
155 The regex parser returns an AST (abstract syntax tree) of the text,
156 directives, variables, and expressions. All of the different template
157 syntaxes compile to the same AST format. The AST is composed only of
158 scalars and arrayrefs and is suitable for sending to JavaScript via
159 JSON or sharing with other languages. The parse_tree method is used
160 for returning this AST.
161
162 Once at the AST stage, there are two modes of operation. Alloy can
163 either operate directly on the AST using the Play role, or it can com‐
164 pile the AST to perl code via the Compile role, and then execute the
165 code. To use the perl code route, you must set the COMPILE_PERL flag
166 to 1. If you are running in a cached environment such as mod_perl,
167 this is the fastest option. If you are running in a non-cached envi‐
168 ronment, the Playing or the AST is generally faster. The AST method is
169 also more secure as cached AST won't ever eval "perl" (assuming PERL
170 blocks are disabled).
171
173 Template::Alloy has split out its functionality into discrete roles.
174 In Template::Toolkit, this functionality is split into separate
175 classes. The roles in Template::Alloy simply add on more methods to
176 the main class. When Perl 6 arrives, these roles will be translated
177 into true Roles.
178
179 The following is a list of roles used by Template::Alloy.
180
181 Template::Alloy::Compile - Compile-to-perl role
182 Template::Alloy::HTE - HTML::Template::Expr role
183 Template::Alloy::Operator - Operator role
184 Template::Alloy::Parse - Parse-to-AST role
185 Template::Alloy::Play - Play-AST role
186 Template::Alloy::Tmpl - Text::Tmpl role
187 Template::Alloy::TT - Template::Toolkit role
188 Template::Alloy::Velocity - Velocity role
189 Template::Alloy::VMethod - Virtual methods role
190
191 Template::Alloy automatically loads the roles when they are needed or
192 requested - but not sooner (with the exception of the Operator role and
193 the VMethod role which are always needed and always loaded). This is
194 good for a CGI environment. In mod_perl you may want to preload a role
195 to make the most of shared memory. You may do this by passing either
196 the role name or a method supplied by that role.
197
198 # import roles necessary for running TT
199 use Template::Alloy qw(Parse Play Compile TT);
200
201 # import roles based on methods
202 use Template::Alloy qw(parse_tree play_tree compile_tree process);
203
204 Note: importing roles by method names does not import them into the
205 current namespace - it is autoloading the role and methods into the
206 Template::Alloy namespace. To help make this more clear you may use
207 the following syntax as well.
208
209 # import roles necessary for running TT
210 use Template::Alloy load => qw(Parse Play Compile TT);
211
212 # import roles based on methods
213 use Template::Alloy load => qw(process parse_tree play_tree compile_tree);
214
215 # import roles based on methods
216 use Template::Alloy
217 Parse => 1,
218 Play => 1,
219 Compile => 1,
220 TT => 1;
221
222 Even with all roles loaded Template::Alloy is still relatively small.
223 You can load all of the roles by pass "all" to the use statement.
224
225 use Template::Alloy 'all';
226
227 # or
228 use Template::Alloy load => 'all';
229
230 # or
231 use Template::Alloy all => 1;
232
233 As a final option, Template::Alloy also includes the ability to stand-
234 in for other template modules. It is able to do this because it sup‐
235 ports the majority of the interface of the other template systems. You
236 can do this in the following way:
237
238 use Template::Alloy qw('Text::Tmpl', 'HTML::Template');
239
240 # or
241 use Template::Alloy load => qw('Text::Tmpl', 'HTML::Template');
242
243 # or
244 use Template::Alloy
245 'Text::Tmpl' => 1,
246 'HTML::Template' => 1;
247
248 Note that the use statement will die if any of the passed module names
249 are already loaded and not subclasses of Template::Alloy. This will
250 avoid thinking that you are using Template::Alloy when you really
251 aren't. Using the 'all' option won't automatically do this - you must
252 mention the "stood-in" modules by name.
253
254 The following modules may be "stood-in" for:
255
256 Template
257 Text::Tmpl
258 HTML::Template
259 HTML::Template::Expr
260
261 This feature is intended to make using Template::Alloy with existing
262 code easier. Most cases should work just fine. Almost all syntax will
263 just work (except Alloy may make some things work that were previously
264 broken). However Template::Alloy doesn't support 100% of the interface
265 of any of the template systems. If you are using "fea‐
266 tures-on-the-edge" then you may need to re-write portions of your code
267 that interact with the template system.
268
270 · Add more POD and examples for all of the various syntaxes.
271
272 · Allow dispatch to different syntaxes based on file extension.
273
274 · Cleanup operator API to allow for easier full customization of
275 operators.
276
277 · Give better examples of overriding directives, syntax, and opera‐
278 tors.
279
280 · Include ASP style.
281
282 · Include HTML::Parser variants such as TAL and Seamstress.
283
285 The following section lists most of the publicly available methods.
286 Some less commonly used public methods are listed later in this docu‐
287 ment.
288
289 "new"
290 my $obj = Template::Alloy->new({
291 INCLUDE_PATH => ['/my/path/to/content', '/my/path/to/content2'],
292 });
293
294 Arguments may be passed as a hash or as a hashref. Returns a Tem‐
295 plate::Alloy object.
296
297 There are currently no errors during Template::Alloy object cre‐
298 ation. If you are using the HTML::Template interface, this is dif‐
299 ferent behavior. The document is not parsed until the output or
300 process methods are called.
301
302 "process"
303 This is the TT interface for starting processing. Any errors that
304 result in the template processing being stopped will be stored and
305 available via the ->error method.
306
307 my $t = Template::Alloy->new;
308 $t->process($in, $swap, $out)
309 ⎪⎪ die $t->error;
310
311 Process takes three arguments.
312
313 The $in argument can be any one of:
314
315 String containing the filename of the template to be processed. The filename should
316 be relative to INCLUDE_PATH. (See INCLUDE_PATH, ABSOLUTE, and RELATIVE configuration items).
317 In memory caching and file side caching are available for this type.
318
319 A reference to a scalar containing the contents of the template to be processed.
320
321 A coderef that will be called to return the contents of the template.
322
323 An open filehandle that will return the contents of the template when read.
324
325 The $swap argument should be hashref containing key value pairs
326 that will be available to variables swapped into the template.
327 Values can be hashrefs, hashrefs of hashrefs and so on, arrayrefs,
328 arrayrefs of arrayrefs and so on, coderefs, objects, and simple
329 scalar values such as numbers and strings. See the section on
330 variables.
331
332 The $out argument can be any one of:
333
334 undef - meaning to print the completed template to STDOUT.
335
336 String containing a filename. The completed template will be placed in the file.
337
338 A reference to a string. The contents will be appended to the scalar reference.
339
340 A coderef. The coderef will be called with the contents as a single argument.
341
342 An object that can run the method "print". The contents will be passed as
343 a single argument to print.
344
345 An arrayref. The contents will be pushed onto the array.
346
347 An open filehandle. The contents will be printed to the open handle.
348
349 Additionally - the $out argument can be configured using the OUTPUT
350 configuration item.
351
352 The process method defaults to using the "cet" syntax which will
353 parse TT3 and most TT2 documents. To parse HT or HTE documents,
354 you must pass the SYNTAX configuration item to the "new" method.
355 All calls to process would then default to HTE syntax.
356
357 my $obj = Template::Alloy->new(SYNTAX => 'hte');
358
359 "process_simple"
360 Similar to the process method but with the following restrictions:
361
362 The $in parameter is limited to a filename or a reference a string
363 containing the contents.
364
365 The $out parameter may only be a reference to a scalar string that
366 output will be appended to.
367
368 Additionally, the following configuration variables will be
369 ignored: VARIABLES, PRE_DEFINE, BLOCKS, PRE_PROCESS, PROCESS,
370 POST_PROCESS, AUTO_RESET, OUTPUT.
371
372 "error"
373 Should something go wrong during a "process" command, the error
374 that occurred can be retrieved via the error method.
375
376 $obj->process('somefile.html', {a => 'b'}, \$string_ref)
377 ⎪⎪ die $obj->error;
378
379 "output"
380 HTML::Template way to process a template. The output method
381 requires that a filename, filehandle, scalarref, or arrayref argu‐
382 ment was passed to the new method. All of the HT calling conven‐
383 tions for new are supported. The key difference is that Alloy will
384 not actually process the template until the output method is
385 called.
386
387 my $obj = Template::Alloy->new(filename => 'myfile.html');
388 $obj->param(\%swap);
389 print $obj->output;
390
391 See the HTML::Template documentation for more information.
392
393 The output method defaults to using the "hte" syntax which will
394 parse HTE and HT documents. To parse TT3 or TT2 documents, you
395 must pass the SYNTAX configuration item to the "new" method. All
396 calls to process would then default to TT3 syntax.
397
398 my $obj = Template::Alloy->new(SYNTAX => 'tt3');
399
400 Any errors that occur during the output method will die with the
401 error as the die value.
402
403 "param"
404 HTML::Template way to get or set variable values that will be used
405 by the output method.
406
407 my $val = $obj->param('key'); # get one value
408
409 $obj->param(key => $val); # set one value
410
411 $obj->param(key => $val, key2 => $val2); # set multiple
412
413 $obj->param({key => $val, key2 => $val2}); # set multiple
414
415 See the HTML::Template documentation for more information.
416
417 Note: Alloy does not support the die_on_bad_params configuration.
418 This is because Alloy does not resolve variable names until the
419 output method is called.
420
421 "define_vmethod"
422 This method is available for defining extra Virtual methods or fil‐
423 ters. This method is similar to Template::Stash::define_vmethod.
424
425 Template::Alloy->define_vmethod(
426 'text',
427 reverse => sub { my $item = shift; return scalar reverse $item },
428 );
429
430 "register_function"
431 This is the HTML::Template way of defining text vmethods. It is
432 the same as calling define_vmethod with "text" as the first argu‐
433 ment.
434
435 Template::Alloy->register_function(
436 reverse => sub { my $item = shift; return scalar reverse $item },
437 );
438
439 "define_directive"
440 This method can be used for adding new directives or overridding
441 existing ones.
442
443 Template::Alloy->define_directive(
444 MYDIR => {
445 parse_sub => sub {}, # parse additional items in the tag
446 play_sub => sub {
447 my ($self, $ref, $node, $out_ref) = @_;
448 $$out_ref .= "I always say the same thing!";
449 return;
450 },
451 is_block => 1, # is this block like
452 is_postop => 0, # not a post operative directive
453 no_interp => 1, # no interpolation in this block
454 continues => undef, # it doesn't "continue" any other directives
455 },
456 );
457
458 Now with a template like:
459
460 my $str = "([% MYDIR %]This is something[% END %])";
461 Template::Alloy->new->process(\$str);
462
463 You will get:
464
465 (I always say the same thing!)
466
467 We'll add more details in later revisions of this document.
468
469 "define_syntax"
470 This method can be used for adding other syntaxes to or overridding
471 existing ones in the list of choices available in Alloy. The syn‐
472 tax can be chosen by the SYNTAX configuration item.
473
474 Template::Alloy->define_syntax(
475 my_uber_syntax => sub {
476 my $self = shift;
477 local $self->{'V2PIPE'} = 0;
478 local $self->{'V2EQUALS'} = 0;
479 local $self->{'PRE_CHOMP'} = 0;
480 local $self->{'POST_CHOMP'} = 0;
481 local $self->{'NO_INCLUDES'} = 0;
482 return $self->parse_tree_tt3(@_);
483 },
484 );
485
486 The subroutine that is used must return an opcode tree (AST) that
487 can be played by the execute_tree method.
488
489 "define_operator"
490 This method allows for adding new operators or overriding existing
491 ones.
492
493 Template::Alloy->define_operator({
494 type => 'right', # can be one of prefix, postfix, right, left, none, ternary, assign
495 precedence => 84, # relative precedence for resolving multiple operators without parens
496 symbols => ['foo', 'FOO'], # any mix of chars can be used for the operators
497 play_sub => sub {
498 my ($one, $two) = @_;
499 return "You've been foo'ed ($one, $two)";
500 },
501 });
502
503 You can then use it in a template as in the following:
504
505 my $str = "[% 'ralph' foo 1 + 2 * 3 %]";
506 Template::Alloy->new->process(\$str);
507
508 You will get:
509
510 You've been foo'ed (ralph, 7)
511
512 Future revisions of this document will include more samples. This
513 is an experimental feature and the api will probably change.
514
515 "dump_parse_tree"
516 This method allows for returning a Data::Dumper dump of a parsed
517 template. It is mainly used for testing.
518
519 "dump_parse_expr"
520 This method allows for returning a Data::Dumper dump of a parsed
521 variable. It is mainly used for testing.
522
523 "import"
524 All of the arguments that can be passed to "use" that are listed
525 above in the section dealing with ROLES, can be used with the
526 import method.
527
528 # import by role
529 Template::Alloy->import(qw(Compile Play Parse TT));
530
531 # import by method
532 Template::Alloy->import(qw(compile_tree play_tree parse_tree process));
533
534 # import by "stand-in" class
535 Template::Alloy->import('Text::Tmpl', 'HTML::Template::Expr');
536
537 As mentioned in the ROLE section - arguments passed to import are
538 not imported into current namespace. Roles and methods are only
539 imported into the Template::Alloy namespace.
540
542 This section discusses how to use variables and expressions in the TT
543 mini-language.
544
545 A variable is the most simple construct to insert into the TT mini lan‐
546 guage. A variable name will look for the matching value inside Tem‐
547 plate::Alloys internal stash of variables which is essentially a hash
548 reference. This stash is initially populated by either passing a
549 hashref as the second argument to the process method, or by setting the
550 "VARIABLES" or "PRE_DEFINE" configuration variables.
551
552 If you are using the HT and HTE syntaxes, the VAR, IF, UNLESS, LOOP,
553 and INCLUDE directives will accept a NAME attribute which may only be a
554 single level (non-chained) HTML::Template variable name, or they may
555 accept an EXPR attribute which may be any valid TT3 variable or expres‐
556 sion.
557
558 The following are some sample ways to access variables.
559
560 ### some sample variables
561 my %vars = (
562 one => '1.0',
563 foo => 'bar',
564 vname => 'one',
565 some_code => sub { "You passed me (".join(', ', @_).")" },
566 some_data => {
567 a => 'A',
568 bar => 3234,
569 c => [3, 1, 4, 1, 5, 9],
570 vname => 'one',
571 },
572 my_list => [20 .. 50],
573 cet => Template::Alloy->new,
574 );
575
576 ### pass the variables into the Alloy process
577 $cet->process($template_name, \%vars)
578 ⎪⎪ die $cet->error;
579
580 ### pass the variables during object creation (will be available to every process call)
581 my $cet = Template::Alloy->new(VARIABLES => \%vars);
582
583 GETTING VARIABLES
584
585 Once you have variables defined, they can be used directly in the tem‐
586 plate by using their name in the stash. Or by using the GET directive.
587
588 [% foo %]
589 [% one %]
590 [% GET foo %]
591
592 Would print when processed:
593
594 bar
595 1.0
596 bar
597
598 To access members of a hashref or an arrayref, you can chain together
599 the names using a ".".
600
601 [% some_data.a %]
602 [% my_list.0] [% my_list.1 %] [% my_list.-1 %]
603 [% some_data.c.2 %]
604
605 Would print:
606
607 A
608 20 21 50
609 4
610
611 If the value of a variable is a code reference, it will be called. You
612 can add a set of parenthesis and arguments to pass arguments. Argu‐
613 ments are variables and can be as complex as necessary.
614
615 [% some_code %]
616 [% some_code() %]
617 [% some_code(foo) %]
618 [% some_code(one, 2, 3) %]
619
620 Would print:
621
622 You passed me ().
623 You passed me ().
624 You passed me (bar).
625 You passed me (1.0, 2, 3).
626
627 If the value of a variable is an object, methods can be called using
628 the "." operator.
629
630 [% cet %]
631
632 [% cet.dump_parse_expr('1 + 2').replace('\s+', ' ') %]
633
634 Would print something like:
635
636 Template::Alloy=HASH(0x814dc28)
637
638 $VAR1 = [ [ undef, '+', '1', '2' ], 0 ];
639
640 Each type of data (string, array and hash) have virtual methods associ‐
641 ated with them. Virtual methods allow for access to functions that are
642 commonly used on those types of data. For the full list of built in
643 virtual methods, please see the section titled VIRTUAL METHODS
644
645 [% foo.length %]
646 [% my_list.size %]
647 [% some_data.c.join(" ⎪ ") %]
648
649 Would print:
650
651 3
652 31
653 3 ⎪ 1 ⎪ 4 ⎪ 5 ⎪ 9
654
655 It is also possible to "interpolate" variable names using a "$". This
656 allows for storing the name of a variable inside another variable. If
657 a variable name is a little more complex it can be embedded inside of
658 "${" and "}".
659
660 [% $vname %]
661 [% ${vname} %]
662 [% ${some_data.vname} %]
663 [% some_data.$foo %]
664 [% some_data.${foo} %]
665
666 Would print:
667
668 1.0
669 1.0
670 1.0
671 3234
672 3234
673
674 In Alloy it is also possible to embed any expression (non-directive) in
675 "${" and "}" and it is possible to use non-integers for array access.
676 (This is not available in TT2)
677
678 [% ['a'..'z'].${ 2.3 } %]
679 [% {ab => 'AB'}.${ 'a' ~ 'b' } %]
680 [% color = qw/Red Blue/; FOR [1..4] ; color.${ loop.index % color.size } ; END %]
681
682 Would print:
683
684 c
685 AB
686 RedBlueRedBlue
687
688 SETTING VARIABLES.
689
690 To define variables during processing, you can use the = operator. In
691 most cases this is the same as using the SET directive.
692
693 [% a = 234 %][% a %]
694 [% SET b = "Hello" %][% b %]
695
696 Would print:
697
698 234
699 Hello
700
701 It is also possible to create arrayrefs and hashrefs.
702
703 [% a = [1, 2, 3] %]
704 [% b = {key1 => 'val1', 'key2' => 'val2'} %]
705
706 [% a.1 %]
707 [% b.key1 %] [% b.key2 %]
708
709 Would print:
710
711 2
712 val1 val2
713
714 It is possible to set multiple values in the same SET directive.
715
716 [% SET a = 'A'
717 b = 'B'
718 c = 'C' %]
719 [% a %] [% b %] [% c %]
720
721 Would print:
722
723 A B C
724
725 It is also possible to unset variables, or to set members of nested
726 data structures.
727
728 [% a = 1 %]
729 [% SET a %]
730
731 [% b.0.c = 37 %]
732
733 ([% a %])
734 [% b.0.c %]
735
736 Would print
737
738 ()
739 37
740
742 The following are the types of literals (numbers and strings) and con‐
743 structors (hash and array constructs) allowed in Alloy. They can be
744 used as arguments to functions, in place of variables in directives,
745 and in place of variables in expressions. In Alloy it is also possible
746 to call virtual methods on literal values.
747
748 Integers and Numbers.
749 [% 23423 %] Prints an integer.
750 [% 3.14159 %] Prints a number.
751 [% pi = 3.14159 %] Sets the value of the variable.
752 [% 3.13159.length %] Prints 7 (the string length of the number)
753
754 Scientific notation is supported.
755
756 [% 314159e-5 + 0 %] Prints 3.14159.
757
758 [% .0000001.fmt('%.1e') %] Prints 1.0e-07
759
760 Hexidecimal input is also supported.
761
762 [% 0xff + 0 %] Prints 255
763
764 [% 48875.fmt('%x') %] Prints beeb
765
766 Single quoted strings.
767 Returns the string. No variable interpolation happens.
768
769 [% 'foobar' %] Prints "foobar".
770 [% '$foo\n' %] Prints "$foo\\n". # the \\n is a literal "\" and an "n"
771 [% 'That\'s nice' %] Prints "That's nice".
772 [% str = 'A string' %] Sets the value of str.
773 [% 'A string'.split %] Splits the string on ' ' and returns the list.
774
775 Note: virtual methods can only be used on literal strings in Alloy,
776 not in TT.
777
778 You may also embed the current tags in strings (Alloy only).
779
780 [% '[% 1 + 2 %]' ⎪ eval %] Prints "3"
781
782 Double quoted strings.
783 Returns the string. Variable interpolation happens.
784
785 [% "foobar" %] Prints "foobar".
786 [% "$foo" %] Prints "bar" (assuming the value of foo is bar).
787 [% "${foo}" %] Prints "bar" (assuming the value of foo is bar).
788 [% "foobar\n" %] Prints "foobar\n". # the \n is a newline.
789 [% str = "Hello" %] Sets the value of str.
790 [% "foo".replace('foo','bar') %] Prints "bar".
791
792 Note: virtual methods can only be used on literal strings in Alloy,
793 not in TT.
794
795 You may also embed the current tags in strings (Alloy only).
796
797 [% "[% 1 + 2 %]" ⎪ eval %] Prints "3"
798
799 Array Constructs.
800 [% [1, 2, 3] %] Prints something like ARRAY(0x8309e90).
801 [% array1 = [1 .. 3] %] Sets the value of array1.
802 [% array2 = [foo, 'a', []] %] Sets the value of array2.
803 [% [4, 5, 6].size %] Prints 3.
804 [% [7, 8, 9].reverse.0 %] Prints 9.
805
806 Note: virtual methods can only be used on array contructs in Alloy,
807 not in TT.
808
809 Quoted Array Constructs.
810 [% qw/1 2 3/ %] Prints something like ARRAY(0x8309e90).
811 [% array1 = qw{Foo Bar Baz} %] Sets the value of array1.
812 [% qw[4 5 6].size %] Prints 3.
813 [% qw(Red Blue).reverse.0 %] Prints Blue.
814
815 Note: this works in Alloy and is planned for TT3.
816
817 Hash Constructs.
818 [% {foo => 'bar'} %] Prints something like HASH(0x8305880)
819 [% hash = {foo => 'bar', c => {}} %] Sets the value of hash.
820 [% {a => 'A', b => 'B'}.size %] Prints 2.
821 [% {'a' => 'A', 'b' => 'B'}.size %] Prints 2.
822 [% name = "Tom" %]
823 [% {Tom => 'You are Tom',
824 Kay => 'You are Kay'}.$name %] Prints You are Tom
825
826 Note: virtual methods can only be used on hash contructs in Alloy,
827 not in TT.
828
829 Regex Constructs.
830 [% /foo/ %] Prints (?-xism:foo)
831 [% a = /(foo)/i %][% "FOO".match(a).0 %] Prints FOO
832
833 Note: this works in Alloy and is planned for TT3.
834
836 Virtual methods (vmethods) are a TT feature that allow for operating on
837 the swapped template variables.
838
839 This document shows some samples of using vmethods. For a full listing
840 of available virtual methods, see Template::Alloy::VMethod.
841
843 Expressions are one or more variables or literals joined together with
844 operators. An expression can be used anywhere a variable can be used
845 with the exception of the variable name in the SET directive, and the
846 filename of PROCESS, INCLUDE, WRAPPER, and INSERT.
847
848 For a full listing of operators, see Template::Alloy::Operator.
849
850 The following section shows some samples of expressions. For a full
851 list of available operators, please see the section titled OPERATORS.
852
853 [% 1 + 2 %] Prints 3
854 [% 1 + 2 * 3 %] Prints 7
855 [% (1 + 2) * 3 %] Prints 9
856
857 [% x = 2 %] # assignments don't return anything
858 [% (x = 2) %] Prints 2 # unless they are in parens
859 [% y = 3 %]
860 [% x * (y - 1) %] Prints 4
861
863 This section contains the alphabetical list of DIRECTIVES available in
864 Alloy. DIRECTIVES are the "functions" and control structures that work
865 in the various mini-languages. For further discussion and examples
866 beyond what is listed below, please refer to the TT directives documen‐
867 tation or to the appropriate documentation for the particular direc‐
868 tive.
869
870 The examples given in this section are done using the Template::Toolkit
871 syntax, but can be done in any of the various syntaxes. See Tem‐
872 plate::Alloy::TT, Template::Alloy::HTE, Template::Alloy::Tmpl, and Tem‐
873 plate::Alloy::Velocity.
874
875 [% IF 1 %]One[% END %]
876 [% FOREACH a = [1 .. 3] %]
877 a = [% a %]
878 [% END %]
879
880 [% SET a = 1 %][% SET a = 2 %][% GET a %]
881
882 In TT multiple directives can be inside the same set of '[%' and '%]'
883 tags as long as they are separated by space or semi-colons (;) (The
884 Alloy version of Tmpl allows multiple also - but none of the other syn‐
885 taxes do). Any block directive that can also be used as a post-opera‐
886 tive directive (such as IF, WHILE, FOREACH, UNLESS, FILTER, and WRAP‐
887 PER) must be separated from preceding directives with a semi-colon if
888 it is being used as a block directive. It is more safe to always use a
889 semi-colon. Note: separating by space is only available in Alloy but
890 is a planned TT3 feature.
891
892 [% SET a = 1 ; SET a = 2 ; GET a %]
893 [% SET a = 1
894 SET a = 2
895 GET a
896 %]
897
898 [% GET 1
899 IF 0 # is a post-operative
900 GET 2 %] # prints 2
901
902 [% GET 1;
903 IF 0 # it is block based
904 GET 2
905 END
906 %] # prints 1
907
908 The following is the list of directives.
909
910 "BLOCK"
911 Saves a block of text under a name for later use in PROCESS,
912 INCLUDE, and WRAPPER directives. Blocks may be placed anywhere
913 within the template being processed including after where they
914 are used.
915
916 [% BLOCK foo %]Some text[% END %]
917 [% PROCESS foo %]
918
919 Would print
920
921 Some text
922
923 [% INCLUDE foo %]
924 [% BLOCK foo %]Some text[% END %]
925
926 Would print
927
928 Some text
929
930 Anonymous BLOCKS can be used for capturing.
931
932 [% a = BLOCK %]Some text[% END %][% a %]
933
934 Would print
935
936 Some text
937
938 Anonymous BLOCKS can be used with macros.
939
940 "BREAK"
941 Alias for LAST. Used for exiting FOREACH and WHILE loops.
942
943 "CALL"
944 Calls the variable (and any underlying coderefs) as in the GET
945 method, but always returns an empty string.
946
947 "CASE"
948 Used with the SWITCH directive. See the "SWITCH" directive.
949
950 "CATCH"
951 Used with the TRY directive. See the "TRY" directive.
952
953 "CLEAR"
954 Clears any of the content currently generated in the innermost
955 block or template. This can be useful when used in conjunction
956 with the TRY statement to clear generated content if an error
957 occurs later.
958
959 "COMMENT"
960 Will comment out any text found between open and close tags.
961 Note, that the intermediate items are still parsed and END tags
962 must align - but the parsed content will be discarded.
963
964 [% COMMENT %]
965 This text won't be shown.
966 [% IF 1 %]And this won't either.[% END %]
967 [% END %]
968
969 "CONFIG"
970 Allow for changing the value of some compile time and runtime
971 configuration options.
972
973 [% CONFIG
974 ANYCASE => 1
975 PRE_CHOMP => '-'
976 %]
977
978 The following compile time configuration options may be set:
979
980 ANYCASE
981 AUTO_EVAL
982 CACHE_STR_REFS
983 INTERPOLATE
984 POST_CHOMP
985 PRE_CHOMP
986 SEMICOLONS
987 SHOW_UNDEFINED_INTERP
988 SYNTAX
989 V1DOLLAR
990 V2EQUALS
991 V2PIPE
992
993 The following runtime configuration options may be set:
994
995 DUMP
996 VMETHOD_FUNCTIONS
997
998 If non-named parameters as passed, they will show the current
999 configuration:
1000
1001 [% CONFIG ANYCASE, PRE_CHOMP %]
1002
1003 CONFIG ANYCASE = undef
1004 CONFIG PRE_CHOMP = undef
1005
1006 "DEBUG"
1007 Used to reset the DEBUG_FORMAT configuration variable, or to
1008 turn DEBUG statements on or off. This only has effect if the
1009 DEBUG_DIRS or DEBUG_ALL flags were passed to the DEBUG configu‐
1010 ration variable.
1011
1012 [% DEBUG format '($file) (line $line) ($text)' %]
1013 [% DEBUG on %]
1014 [% DEBUG off %]
1015
1016 "DEFAULT"
1017 Similar to SET, but only sets the value if a previous value was
1018 not defined or was zero length.
1019
1020 [% DEFAULT foo = 'bar' %][% foo %] => 'bar'
1021
1022 [% foo = 'baz' %][% DEFAULT foo = 'bar' %][% foo %] => 'baz'
1023
1024 "DUMP"
1025 DUMP inserts a Data::Dumper printout of the variable or expres‐
1026 sion. If no argument is passed it will dump the entire con‐
1027 tents of the current variable stash (with private keys
1028 removed).
1029
1030 The output also includes the current file and line number that
1031 the DUMP directive was called from.
1032
1033 See the DUMP configuration item for ways to customize and con‐
1034 trol the output available to the DUMP directive.
1035
1036 [% DUMP %] # dumps everything
1037
1038 [% DUMP 1 + 2 %]
1039
1040 "ELSE"
1041 Used with the IF directive. See the "IF" directive.
1042
1043 "ELSIF"
1044 Used with the IF directive. See the "IF" directive.
1045
1046 "END"
1047 Used to end a block directive.
1048
1049 "EVAL"
1050 Same as the EVALUATE directive.
1051
1052 "EVALUATE"
1053 Introduced by the Velocity templating language. Parses and
1054 processes the contents of the passed item. This is similar to
1055 the eval filter, but Velocity needs a directive. Named argu‐
1056 ments may be used for reconfiguring the parser. Any of the
1057 items that can be passed to the CONFIG directive may be passed
1058 here.
1059
1060 [% EVALUATE "[% 1 + 3 %]" %]
1061
1062 [% foo = "bar" %]
1063 [% EVALUATE "<TMPL_VAR foo>" SYNTAX => 'ht' %]
1064
1065 "FILTER"
1066 Used to apply different treatments to blocks of text. It may
1067 operate as a BLOCK directive or as a post operative directive.
1068 Alloy supports all of the filters in Template::Filters. The
1069 lines between scalar virtual methods and filters is blurred (or
1070 non-existent) in Alloy. Anything that is a scalar virtual
1071 method may be used as a FILTER.
1072
1073 TODO - enumerate the at least 7 ways to pass and use filters.
1074
1075 '⎪' Alias for the FILTER directive. Note that ⎪ is similar to the
1076 '.' in Template::Alloy. Therefore a pipe cannot be used
1077 directly after a variable name in some situations (the pipe
1078 will act only on that variable). This is the behavior employed
1079 by TT3. To get the TT2 behavior for a PIPE, use the V2PIPE
1080 configuration item.
1081
1082 "FINAL"
1083 Used with the TRY directive. See the "TRY" directive.
1084
1085 "FOR"
1086 Alias for FOREACH
1087
1088 "FOREACH"
1089 Allows for iterating over the contents of any arrayref. If the
1090 variable is not an arrayref, it is automatically promoted to
1091 one.
1092
1093 [% FOREACH i IN [1 .. 3] %]
1094 The variable i = [% i %]
1095 [%~ END %]
1096
1097 [% a = [1 .. 3] %]
1098 [% FOREACH j IN a %]
1099 The variable j = [% j %]
1100 [%~ END %]
1101
1102 Would print:
1103
1104 The variable i = 1
1105 The variable i = 2
1106 The variable i = 3
1107
1108 The variable j = 1
1109 The variable j = 2
1110 The variable j = 3
1111
1112 You can also use the "=" instead of "IN" or "in".
1113
1114 [% FOREACH i = [1 .. 3] %]
1115 The variable i = [% i %]
1116 [%~ END %]
1117
1118 Same as before.
1119
1120 Setting into a variable is optional.
1121
1122 [% a = [1 .. 3] %]
1123 [% FOREACH a %] Hi [% END %]
1124
1125 Would print:
1126
1127 hi hi hi
1128
1129 If the item being iterated is a hashref and the FOREACH does
1130 not set into a variable, then values of the hashref are copied
1131 into the variable stash.
1132
1133 [% FOREACH [{a => 1}, {a => 2}] %]
1134 Key a = [% a %]
1135 [%~ END %]
1136
1137 Would print:
1138
1139 Key a = 1
1140 Key a = 2
1141
1142 The FOREACH process uses the Template::Alloy::Iterator class to
1143 handle iterations (It is compatible with Template::Iterator).
1144 During the FOREACH loop an object blessed into the iterator
1145 class is stored in the variable "loop".
1146
1147 The loop variable provides the following information during a
1148 FOREACH:
1149
1150 index - the current index
1151 max - the max index of the list
1152 size - the number of items in the list
1153 count - index + 1
1154 number - index + 1
1155 first - true if on the first item
1156 last - true if on the last item
1157 next - return the next item in the list
1158 prev - return the previous item in the list
1159
1160 The following:
1161
1162 [% FOREACH [1 .. 3] %] [% loop.count %]/[% loop.size %] [% END %]
1163
1164 Would print:
1165
1166 1/3 2/3 3/3
1167
1168 The iterator is also available using a plugin. This allows for
1169 access to multiple "loop" variables in a nested FOREACH direc‐
1170 tive.
1171
1172 [%~ USE outer_loop = Iterator(["a", "b"]) %]
1173 [%~ FOREACH i = outer_loop %]
1174 [%~ FOREACH j = ["X", "Y"] %]
1175 [% outer_loop.count %]-[% loop.count %] = ([% i %] and [% j %])
1176 [%~ END %]
1177 [%~ END %]
1178
1179 Would print:
1180
1181 1-1 = (a and X)
1182 1-2 = (a and Y)
1183 2-1 = (b and X)
1184 2-2 = (b and Y)
1185
1186 FOREACH may also be used as a post operative directive.
1187
1188 [% "$i" FOREACH i = [1 .. 5] %] => 12345
1189
1190 "GET"
1191 Return the value of a variable or expression.
1192
1193 [% GET a %]
1194
1195 The GET keyword may be omitted.
1196
1197 [% a %]
1198
1199 [% 7 + 2 - 3 %] => 6
1200
1201 See the section on VARIABLES.
1202
1203 "IF (IF / ELSIF / ELSE)"
1204 Allows for conditional testing. Expects an expression as its
1205 only argument. If the expression is true, the contents of its
1206 block are processed. If false, the processor looks for an
1207 ELSIF block. If an ELSIF's expression is true then it is pro‐
1208 cessed. Finally it looks for an ELSE block which is processed
1209 if none of the IF or ELSIF's expressions were true.
1210
1211 [% IF a == b %]A equaled B[% END %]
1212
1213 [% IF a == b -%]
1214 A equaled B
1215 [%- ELSIF a == c -%]
1216 A equaled C
1217 [%- ELSE -%]
1218 Couldn't determine that A equaled anything.
1219 [%- END %]
1220
1221 IF may also be used as a post operative directive.
1222
1223 [% 'A equaled B' IF a == b %]
1224
1225 Note: If you are using HTML::Template style documents, the
1226 TMPL_IF tag parses using the limited HTML::Template parsing
1227 rules. However, you may use EXPR="" to embed a TT3 style
1228 expression.
1229
1230 "INCLUDE"
1231 Parse the contents of a file or block and insert them. Vari‐
1232 ables defined or modifications made to existing variables are
1233 discarded after a template is included.
1234
1235 [% INCLUDE path/to/template.html %]
1236
1237 [% INCLUDE "path/to/template.html" %]
1238
1239 [% file = "path/to/template.html" %]
1240 [% INCLUDE $file %]
1241
1242 [% BLOCK foo %]This is foo[% END %]
1243 [% INCLUDE foo %]
1244
1245 Arguments may also be passed to the template:
1246
1247 [% INCLUDE "path/to/template.html" a = "An arg" b = "Another arg" %]
1248
1249 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1250 or RELATIVE configuration items are set.
1251
1252 Multiple filenames can be passed by separating them with a
1253 plus, a space, or commas (TT2 doesn't support the comma). Any
1254 supplied arguments will be used on all templates.
1255
1256 [% INCLUDE "path/to/template.html",
1257 "path/to/template2.html" a = "An arg" b = "Another arg" %]
1258
1259 "INSERT"
1260 Insert the contents of a file without template parsing.
1261
1262 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1263 or RELATIVE configuration items are set.
1264
1265 Multiple filenames can be passed by separating them with a
1266 plus, a space, or commas (TT2 doesn't support the comma).
1267
1268 [% INSERT "path/to/template.html",
1269 "path/to/template2.html" %]
1270
1271 "LAST"
1272 Used to exit out of a WHILE or FOREACH loop.
1273
1274 "LOOP"
1275 This directive operates similar to the HTML::Template loop
1276 directive. The LOOP directive expects a single variable name.
1277 This variable name should point to an arrayref of hashrefs.
1278 The keys of each hashref will be added to the variable stash
1279 when it is iterated.
1280
1281 [% var a = [{b => 1}, {b => 2}, {b => 3}] %]
1282
1283 [% LOOP a %] ([% b %]) [% END %]
1284
1285 Would print:
1286
1287 (1) (2) (3)
1288
1289 If Alloy is in HT mode and GLOBAL_VARS is false, the contents
1290 of the hashref will be the only items available during the loop
1291 iteration.
1292
1293 If LOOP_CONTEXT_VARS is true, and $QR_PRIVATE is false (default
1294 when called through the output method), then the variables
1295 __first__, __last__,
1296 __inner__, __odd__, and __counter__ will be set. See the
1297 HTML::Template loop_context_vars configuration item for more
1298 information.
1299
1300 "MACRO"
1301 Takes a directive and turns it into a variable that can take
1302 arguments.
1303
1304 [% MACRO foo(i, j) BLOCK %]You passed me [% i %] and [% j %].[% END %]
1305
1306 [%~ foo("a", "b") %]
1307 [% foo(1, 2) %]
1308
1309 Would print:
1310
1311 You passed me a and b.
1312 You passed me 1 and 2.
1313
1314 Another example:
1315
1316 [% MACRO bar(max) FOREACH i = [1 .. max] %]([% i %])[% END %]
1317
1318 [%~ bar(4) %]
1319
1320 Would print:
1321
1322 (1)(2)(3)(4)
1323
1324 "META"
1325 Used to define variables that will be available via either the
1326 template or component namespace.
1327
1328 Once defined, they cannot be overwritten.
1329
1330 [% template.foobar %]
1331 [%~ META foobar = 'baz' %]
1332 [%~ META foobar = 'bing' %]
1333
1334 Would print:
1335
1336 baz
1337
1338 "NEXT"
1339 Used to go to the next iteration of a WHILE or FOREACH loop.
1340
1341 "PERL"
1342 Only available if the EVAL_PERL configuration item is true
1343 (default is false).
1344
1345 Allow eval'ing the block of text as perl. The block will be
1346 parsed and then eval'ed.
1347
1348 [% a = "BimBam" %]
1349 [%~ PERL %]
1350 my $a = "[% a %]";
1351 print "The variable \$a was \"$a\"";
1352 $stash->set('b', "FooBar");
1353 [% END %]
1354 [% b %]
1355
1356 Would print:
1357
1358 The variable $a was "BimBam"
1359 FooBar
1360
1361 During execution, anything printed to STDOUT will be inserted
1362 into the template. Also, the $stash and $context variables are
1363 set and are references to objects that mimic the interface pro‐
1364 vided by Template::Context and Template::Stash. These are pro‐
1365 vided for compatibility only. $self contains the current Tem‐
1366 plate::Alloy object.
1367
1368 "PROCESS"
1369 Parse the contents of a file or block and insert them. Unlike
1370 INCLUDE, no variable localization happens so variables defined
1371 or modifications made to existing variables remain after the
1372 template is processed.
1373
1374 [% PROCESS path/to/template.html %]
1375
1376 [% PROCESS "path/to/template.html" %]
1377
1378 [% file = "path/to/template.html" %]
1379 [% PROCESS $file %]
1380
1381 [% BLOCK foo %]This is foo[% END %]
1382 [% PROCESS foo %]
1383
1384 Arguments may also be passed to the template:
1385
1386 [% PROCESS "path/to/template.html" a = "An arg" b = "Another arg" %]
1387
1388 Filenames must be relative to INCLUDE_PATH unless the ABSOLUTE
1389 or RELATIVE configuration items are set.
1390
1391 Multiple filenames can be passed by separating them with a
1392 plus, a space, or commas (TT2 doesn't support the comma). Any
1393 supplied arguments will be used on all templates.
1394
1395 [% PROCESS "path/to/template.html",
1396 "path/to/template2.html" a = "An arg" b = "Another arg" %]
1397
1398 "RAWPERL"
1399 Only available if the EVAL_PERL configuration item is true
1400 (default is false). Similar to the PERL directive, but you
1401 will need to append to the $output variable rather than just
1402 calling PRINT.
1403
1404 "RETURN"
1405 Used to exit the innermost block or template and continue pro‐
1406 cessing in the surrounding block or template.
1407
1408 "SET"
1409 Used to set variables.
1410
1411 [% SET a = 1 %][% a %] => "1"
1412 [% a = 1 %][% a %] => "1"
1413 [% b = 1 %][% SET a = b %][% a %] => "1"
1414 [% a = 1 %][% SET a %][% a %] => ""
1415 [% SET a = [1, 2, 3] %][% a.1 %] => "2"
1416 [% SET a = {b => 'c'} %][% a.b %] => "c"
1417
1418 "STOP"
1419 Used to exit the entire process method (out of all blocks and
1420 templates). No content will be processed beyond this point.
1421
1422 "SWITCH"
1423 Allow for SWITCH and CASE functionality.
1424
1425 [% a = "hi" %]
1426 [% b = "bar" %]
1427 [% SWITCH a %]
1428 [% CASE "foo" %]a was foo
1429 [% CASE b %]a was bar
1430 [% CASE ["hi", "hello"] %]You said hi or hello
1431 [% CASE DEFAULT %]I don't know what you said
1432 [% END %]
1433
1434 Would print:
1435
1436 You said hi or hello
1437
1438 "TAGS"
1439 Change the type of enclosing braces used to delineate template
1440 tags. This remains in effect until the end of the enclosing
1441 block or template or until the next TAGS directive. Either a
1442 named set of tags must be supplied, or two tags themselves must
1443 be supplied.
1444
1445 [% TAGS html %]
1446
1447 [% TAGS <!-- --> %]
1448
1449 The named tags are (duplicated from TT):
1450
1451 asp => ['<%', '%>' ], # ASP
1452 default => ['\[%', '%\]' ], # default
1453 html => ['<!--', '-->' ], # HTML comments
1454 mason => ['<%', '>' ], # HTML::Mason
1455 metatext => ['%%', '%%' ], # Text::MetaText
1456 php => ['<\?', '\?>' ], # PHP
1457 star => ['\[\*', '\*\]' ], # TT alternate
1458 template => ['\[%', '%\]' ], # Normal Template Toolkit
1459 template1 => ['[\[%]%', '%[%\]]'], # allow TT1 style
1460 tt2 => ['\[%', '%\]' ], # TT2
1461
1462 If custom tags are supplied, by default they are escaped using
1463 quotemeta. You may also pass explicitly quoted strings, or
1464 regular expressions as arguments as well (if your regex begins
1465 with a ', ", or / you must quote it.
1466
1467 [% TAGS [<] [>] %] matches "[<] tag [>]"
1468
1469 [% TAGS '[<]' '[>]' %] matches "[<] tag [>]"
1470
1471 [% TAGS "[<]" "[>]" %] matches "[<] tag [>]"
1472
1473 [% TAGS /[<]/ /[>]/ %] matches "< tag >"
1474
1475 [% TAGS ** ** %] matches "** tag **"
1476
1477 [% TAGS /**/ /**/ %] Throws an exception.
1478
1479 You should be sure that the start tag does not include grouping
1480 parens or INTERPOLATE will not function properly.
1481
1482 "THROW"
1483 Allows for throwing an exception. If the exception is not
1484 caught via the TRY DIRECTIVE, the template will abort process‐
1485 ing of the directive.
1486
1487 [% THROW mytypes.sometime 'Something happened' arg1 => val1 %]
1488
1489 See the TRY directive for examples of usage.
1490
1491 "TRY"
1492 The TRY block directive will catch exceptions that are thrown
1493 while processing its block (It cannot catch parse errors unless
1494 they are in included files or evaltt'ed strings. The TRY
1495 block will then look for a CATCH block that will be processed.
1496 While it is being processed, the "error" variable will be set
1497 with the thrown exception as the value. After the TRY block -
1498 the FINAL block will be ran whether or not an error was thrown
1499 (unless a CATCH block throws an error).
1500
1501 Note: Parse errors cannot be caught unless they are in an eval
1502 FILTER, or are in a separate template being INCLUDEd or PRO‐
1503 CESSed.
1504
1505 [% TRY %]
1506 Nothing bad happened.
1507 [% CATCH %]
1508 Caught the error.
1509 [% FINAL %]
1510 This section runs no matter what happens.
1511 [% END %]
1512
1513 Would print:
1514
1515 Nothing bad happened.
1516 This section runs no matter what happens.
1517
1518 Another example:
1519
1520 [% TRY %]
1521 [% THROW "Something happened" %]
1522 [% CATCH %]
1523 Error: [% error %]
1524 Error.type: [% error.type %]
1525 Error.info: [% error.info %]
1526 [% FINAL %]
1527 This section runs no matter what happens.
1528 [% END %]
1529
1530 Would print:
1531
1532 Error: undef error - Something happened
1533 Error.type: undef
1534 Error.info: Something happened
1535 This section runs no matter what happens.
1536
1537 You can give the error a type and more information including
1538 named arguments. This information replaces the "info" property
1539 of the exception.
1540
1541 [% TRY %]
1542 [% THROW foo.bar "Something happened" "grrrr" foo => 'bar' %]
1543 [% CATCH %]
1544 Error: [% error %]
1545 Error.type: [% error.type %]
1546 Error.info: [% error.info %]
1547 Error.info.0: [% error.info.0 %]
1548 Error.info.1: [% error.info.1 %]
1549 Error.info.args.0: [% error.info.args.0 %]
1550 Error.info.foo: [% error.info.foo %]
1551 [% END %]
1552
1553 Would print something like:
1554
1555 Error: foo.bar error - HASH(0x82a395c)
1556 Error.type: foo.bar
1557 Error.info: HASH(0x82a395c)
1558 Error.info.0: Something happened
1559 Error.info.1: grrrr
1560 Error.info.args.0: Something happened
1561 Error.info.foo: bar
1562
1563 You can also give the CATCH block a type to catch. And you can
1564 nest TRY blocks. If types are specified, Alloy will try and
1565 find the closest matching type. Also, an error object can be
1566 re-thrown using $error as the argument to THROW.
1567
1568 [% TRY %]
1569 [% TRY %]
1570 [% THROW foo.bar "Something happened" %]
1571 [% CATCH bar %]
1572 Caught bar.
1573 [% CATCH DEFAULT %]
1574 Caught default - but rethrew.
1575 [% THROW $error %]
1576 [% END %]
1577 [% CATCH foo %]
1578 Caught foo.
1579 [% CATCH foo.bar %]
1580 Caught foo.bar.
1581 [% CATCH %]
1582 Caught anything else.
1583 [% END %]
1584
1585 Would print:
1586
1587 Caught default - but rethrew.
1588
1589 Caught foo.bar.
1590
1591 "UNLESS"
1592 Same as IF but condition is negated.
1593
1594 [% UNLESS 0 %]hi[% END %] => hi
1595
1596 Can also be a post operative directive.
1597
1598 "USE"
1599 Allows for loading a Template::Toolkit style plugin.
1600
1601 [% USE iter = Iterator(['foo', 'bar']) %]
1602 [%~ iter.get_first %]
1603 [% iter.size %]
1604
1605 Would print:
1606
1607 foo
1608 2
1609
1610 Note that it is possible to send arguments to the new object
1611 constructor. It is also possible to omit the variable name
1612 being assigned. In that case the name of the plugin becomes
1613 the variable.
1614
1615 [% USE Iterator(['foo', 'bar', 'baz']) %]
1616 [%~ Iterator.get_first %]
1617 [% Iterator.size %]
1618
1619 Would print:
1620
1621 foo
1622 3
1623
1624 Plugins that are loaded are looked up for in the namespace
1625 listed in the PLUGIN_BASE directive which defaults to Tem‐
1626 plate::Plugin. So in the previous example, if Template::Tool‐
1627 kit was installed, the iter object would loaded by the class
1628 Template::Plugin::Iterator. In Alloy, an effective way to dis‐
1629 able plugins is to set the PLUGIN_BASE to a non-existent base
1630 such as "_" (In TT it will still fall back to look in Tem‐
1631 plate::Plugin).
1632
1633 Note: The iterator plugin will fall back and use Tem‐
1634 plate::Alloy::Iterator if Template::Toolkit is not installed.
1635 No other plugins come installed with Template::Alloy.
1636
1637 The names of the Plugin being loaded from PLUGIN_BASE are case
1638 insensitive. However, using case insensitive names is bad as
1639 it requires scanning the @INC directories for any module match‐
1640 ing the PLUGIN_BASE and caching the result (OK - not that bad).
1641
1642 If the plugin is not found and the LOAD_PERL directive is set,
1643 then Alloy will try and load a module by that name (note: this
1644 type of lookup is case sensitive and will not scan the @INC
1645 dirs for a matching file).
1646
1647 # The LOAD_PERL directive should be set to 1
1648 [% USE ta = Template::Alloy %]
1649 [%~ ta.dump_parse_expr('2 * 3') %]
1650
1651 Would print:
1652
1653 [[undef, '*', 2, 3], 0];
1654
1655 See the PLUGIN_BASE, and PLUGINS configuration items.
1656
1657 See the documentation for Template::Manual::Plugins.
1658
1659 "VIEW"
1660 Implement a TT style view. For more information, please see
1661 the Template::View documentation. This DIRECTIVE will cor‐
1662 rectly parse the arguments and then pass them along to a newly
1663 created Template::View object. It will fail if Template::View
1664 can not be found.
1665
1666 "WHILE"
1667 Will process a block of code while a condition is true.
1668
1669 [% WHILE i < 3 %]
1670 [%~ i = i + 1 %]
1671 i = [% i %]
1672 [%~ END %]
1673
1674 Would print:
1675
1676 i = 1
1677 i = 2
1678 i = 3
1679
1680 You could also do:
1681
1682 [% i = 4 %]
1683 [% WHILE (i = i - 1) %]
1684 i = [% i %]
1685 [%~ END %]
1686
1687 Would print:
1688
1689 i = 3
1690 i = 2
1691 i = 1
1692
1693 Note that (f = f - 1) is a valid expression that returns the
1694 value of the assignment. The parenthesis are not optional.
1695
1696 WHILE has a built in limit of 1000 iterations. This is con‐
1697 trolled by the global variable $WHILE_MAX in Template::Alloy.
1698
1699 WHILE may also be used as a post operative directive.
1700
1701 [% "$i" WHILE (i = i + 1) < 7 %] => 123456
1702
1703 "WRAPPER"
1704 Block directive. Processes contents of its block and then
1705 passes them in the [% content %] variable to the block or file‐
1706 name listed in the WRAPPER tag.
1707
1708 [% WRAPPER foo b = 23 %]
1709 My content to be processed ([% b %]).[% a = 2 %]
1710 [% END %]
1711
1712 [% BLOCK foo %]
1713 A header ([% a %]).
1714 [% content %]
1715 A footer ([% a %]).
1716 [% END %]
1717
1718 This would print.
1719
1720 A header (2).
1721 My content to be processed (23).
1722 A footer (2).
1723
1724 The WRAPPER directive may also be used as a post operative
1725 directive.
1726
1727 [% BLOCK baz %]([% content %])[% END -%]
1728 [% "foobar" WRAPPER baz %]
1729
1730 Would print
1731
1732 (foobar)');
1733
1734 Multiple filenames can be passed by separating them with a
1735 plus, a space, or commas (TT2 doesn't support the comma). Any
1736 supplied arguments will be used on all templates. Wrappers are
1737 processed in reverse order, so that the first wrapper listed
1738 will surround each subsequent wrapper listed. Variables from
1739 inner wrappers are available to the next wrapper that surrounds
1740 it.
1741
1742 [% WRAPPER "path/to/outer.html",
1743 "path/to/inner.html" a = "An arg" b = "Another arg" %]
1744
1746 HTML::Template templates use directives that look similar to the fol‐
1747 lowing:
1748
1749 <TMPL_VAR NAME="foo">
1750
1751 <TMPL_IF NAME="bar">
1752 BAR
1753 </TMPL_IF>
1754
1755 The normal set of HTML::Template directives are TMPL_VAR, TMPL_IF,
1756 TMPL_ELSE, TMPL_UNLESS, TMPL_INCLUDE, and TMPL_LOOP. These tags should
1757 have either a NAME attribute, an EXPR attribute, or a bare variable
1758 name that is used to specify the value to be operated. If a NAME is
1759 specified, it may only be a single level value (as opposed to a TT
1760 chained variable). In the case of the TMPL_INCLUDE directive, the NAME
1761 is the file to be included.
1762
1763 In Alloy, the EXPR attribute can be used with any of these types to
1764 specify TT compatible variable or expression that will be used for the
1765 value.
1766
1767 <TMPL_VAR NAME="foo"> Prints the value contained in foo
1768 <TMPL_VAR foo> Prints the value contained in foo
1769 <TMPL_VAR EXPR="foo"> Prints the value contained in foo
1770
1771 <TMPL_VAR NAME="foo.bar.baz"> Prints the value contained in {'foo.bar.baz'}
1772 <TMPL_VAR EXPR="foo.bar.baz"> Prints the value contained in {foo}->{bar}->{baz}
1773
1774 <TMPL_IF foo> Prints FOO if foo is true
1775 FOO
1776 </TMPL_IF
1777
1778 <TMPL_UNLESS foo> Prints FOO unless foo is true
1779 FOO
1780 </TMPL_UNLESS
1781
1782 <TMPL_INCLUDE NAME="foo.ht"> Includes the template in "foo.ht"
1783
1784 <TMPL_LOOP foo> Iterates on the arrayref foo
1785 <TMPL_VAR name>
1786 </TMPL_LOOP>
1787
1788 Template::Alloy makes all of the other TT3 directives available in
1789 addition to the normal set of HTML::Template directives. For example,
1790 the following is valid in Alloy.
1791
1792 <TMPL_MACRO bar(n) BLOCK>You said <TMPL_VAR n></TMPL_MACRO>
1793 <TMPL_GET bar("hello")>
1794
1795 The TMPL_VAR tag may also include an optional ESCAPE attribute. This
1796 specifies how the value of the tag should be escaped prior to substi‐
1797 tuting into the template.
1798
1799 Escape value ⎪ Type of escape
1800 ---------------------------------
1801 HTML, 1 ⎪ HTML encoding
1802 URL ⎪ URL encoding
1803 JS ⎪ basic javascript encoding (\n, \r, and \")
1804 NONE, 0 ⎪ No encoding (default).
1805
1806 The TMPL_VAR tag may also include an optional DEFAULT attribute that
1807 contains a string that will be used if the variable returns false.
1808
1809 <TMPL_VAR foo DEFAULT="Foo was false">
1810
1812 Chomping refers to the handling of whitespace immediately before and
1813 immediately after template tags. By default, nothing happens to this
1814 whitespace. Modifiers can be placed just inside the opening and just
1815 before the closing tags to control this behavior.
1816
1817 Additionally, the PRE_CHOMP and POST_CHOMP configuration variables can
1818 be set and will globally control all chomping behavior for tags that do
1819 not have their own chomp modifier. PRE_CHOMP and POST_CHOMP can be set
1820 to any of the following values:
1821
1822 none: 0 + Template::Constants::CHOMP_NONE
1823 one: 1 - Template::Constants::CHOMP_ONE
1824 collapse: 2 = Template::Constants::CHOMP_COLLAPSE
1825 greedy: 3 ~ Template::Constants::CHOMP_GREEDY
1826
1827 CHOMP_NONE
1828 Don't do any chomping. The "+" sign is used to indicate
1829 CHOMP_NONE.
1830
1831 Hello.
1832
1833 [%+ "Hi." +%]
1834
1835 Howdy.
1836
1837 Would print:
1838
1839 Hello.
1840
1841 Hi.
1842
1843 Howdy.
1844
1845 CHOMP_ONE (formerly known as CHOMP_ALL)
1846 Delete any whitespace up to the adjacent newline. The "-" is used
1847 to indicate CHOMP_ONE.
1848
1849 Hello.
1850
1851 [%- "Hi." -%]
1852
1853 Howdy.
1854
1855 Would print:
1856
1857 Hello.
1858 Hi.
1859 Howdy.
1860
1861 CHOMP_COLLAPSE
1862 Collapse adjacent whitespace to a single space. The "=" is used to
1863 indicate CHOMP_COLLAPSE.
1864
1865 Hello.
1866
1867 [%= "Hi." =%]
1868
1869 Howdy.
1870
1871 Would print:
1872
1873 Hello. Hi. Howdy.
1874
1875 CHOMP_GREEDY
1876 Remove all adjacent whitespace. The "~" is used to indicate
1877 CHOMP_GREEDY.
1878
1879 Hello.
1880
1881 [%~ "Hi." ~%]
1882
1883 Howdy.
1884
1885 Would print:
1886
1887 Hello.Hi.Howdy.
1888
1890 The following configuration variables are supported (in alphabetical
1891 order). Note: for further discussion you can refer to the TT config
1892 documentation.
1893
1894 Items may be passed in upper or lower case. If lower case names are
1895 passed they will be resolved to uppercase during the "new" method.
1896
1897 All of the variables in this section can be passed to the "new" con‐
1898 structor.
1899
1900 my $obj = Template::Alloy->new(
1901 VARIABLES => \%hash_of_variables,
1902 AUTO_RESET => 0,
1903 TRIM => 1,
1904 POST_CHOMP => "=",
1905 PRE_CHOMP => "-",
1906 );
1907
1908 ABSOLUTE
1909 Boolean. Default false. Are absolute paths allowed for
1910 included files.
1911
1912 ANYCASE
1913 Allow directive matching to be case insensitive.
1914
1915 [% get 23 %] prints 23 with ANYCASE => 1
1916
1917 AUTO_RESET
1918 Boolean. Default 1. Clear blocks that were set during the
1919 process method.
1920
1921 AUTO_EVAL
1922 Boolean. Default 0 (default 1 in Velocity syntax). If set to
1923 true, double quoted strings will automatically be passed to the
1924 eval filter.
1925
1926 BLOCKS
1927 Only available via when using the process interface.
1928
1929 A hashref of blocks that can be used by the process method.
1930
1931 BLOCKS => {
1932 block_1 => sub { ... }, # coderef that returns a block
1933 block_2 => 'A String', # simple string
1934 },
1935
1936 Note that a Template::Document cannot be supplied as a value
1937 (TT supports this). However, it is possible to supply a value
1938 that is equal to the hashref returned by the load_template
1939 method.
1940
1941 CACHE_SIZE
1942 Number of compiled templates to keep in memory. Default undef.
1943 Undefined means to allow all templates to cache. A value of 0
1944 will force no caching. The cache mechanism will clear tem‐
1945 plates that have not been used recently.
1946
1947 CACHE_STR_REFS
1948 Default 1. If set, any string refs will have an MD5 sum taken
1949 that will then be used for caching the document - both in mem‐
1950 ory and on the file system (if configured). This will give a
1951 significant speed boost. Note that this affects strings passed
1952 to the EVALUATE directive or eval filters as well. It may be
1953 set using the CONFIG directive.
1954
1955 COMPILE_DIR
1956 Base directory to store compiled templates. Default undef.
1957 Compiled templates will only be stored if one of COMPILE_DIR
1958 and COMPILE_EXT is set.
1959
1960 If set, the AST of parsed documents will be cached. If COM‐
1961 PILE_PERL is set, the compiled perl code will also be stored.
1962
1963 COMPILE_EXT
1964 Extension to add to stored compiled template filenames.
1965 Default undef.
1966
1967 If set, the AST of parsed documents will be cached. If COM‐
1968 PILE_PERL is set, the compiled perl code will also be stored.
1969
1970 COMPILE_PERL
1971 Default false.
1972
1973 If set to 1 or 2, will translate the normal AST into a perl 5
1974 code document. This document can then be executed directly,
1975 cached in memory, or cached on the file system depending upon
1976 the configuration items set.
1977
1978 If set to 1, a perl code document will always be generated.
1979
1980 If set to 2, a perl code document will only be generated if an
1981 AST has already been cached for the document. This should give
1982 a speed benefit and avoid extra compilation unless the document
1983 has been used more than once.
1984
1985 If Alloy is running in a cached environment such as mod_perl,
1986 then using compile_perl can offer some speed benefit and makes
1987 Alloy faster than Text::Tmpl and as fast as HTML::Tem‐
1988 plate::Compiled (but Alloy has more features).
1989
1990 If you are not running in a cached environment, such as from
1991 commandline, or from CGI, it is generally faster to only run
1992 from the AST (with COMPILE_PERL => 0).
1993
1994 CONSTANTS
1995 Hashref. Used to define variables that will be "folded" into
1996 the compiled template. Variables defined here cannot be over‐
1997 ridden.
1998
1999 CONSTANTS => {my_constant => 42},
2000
2001 A template containing:
2002
2003 [% constants.my_constant %]
2004
2005 Will have the value 42 compiled in.
2006
2007 Constants defined in this way can be chained as in [% con‐
2008 stant.foo.bar.baz %].
2009
2010 CONSTANT_NAMESPACE
2011 Allow for setting the top level of values passed in CONSTANTS.
2012 Default value is 'constants'.
2013
2014 DEBUG
2015 Takes a list of constants ⎪'ed together which enables different
2016 debugging modes. Alternately the lowercase names may be used
2017 (multiple values joined by a ",").
2018
2019 The only supported TT values are:
2020 DEBUG_UNDEF (2) - debug when an undefined value is used.
2021 DEBUG_DIRS (8) - debug when a directive is used.
2022 DEBUG_ALL (2047) - turn on all debugging.
2023
2024 Either of the following would turn on undef and directive debugging:
2025
2026 DEBUG => 'undef, dirs', # preferred
2027 DEBUG => 2 ⎪ 8,
2028 DEBUG => DEBUG_UNDEF ⎪ DEBUG_DIRS, # constants from Template::Constants
2029
2030 DEBUG_FORMAT
2031 Change the format of messages inserted when DEBUG has
2032 DEBUG_DIRS set on. This essentially the same thing as setting
2033 the format using the DEBUG directive.
2034
2035 DEFAULT
2036 The name of a default template file to use if the passed one is
2037 not found.
2038
2039 DELIMITER
2040 String to use to split INCLUDE_PATH with. Default is :. It is
2041 more straight forward to just send INCLUDE_PATH an arrayref of
2042 paths.
2043
2044 DUMP
2045 Configures the behavior of the DUMP tag. May be set to 0, a
2046 hashref, or another true value. Default is true.
2047
2048 If set to 0, all DUMP directives will do nothing. This is use‐
2049 ful if you would like to turn off the DUMP directives under
2050 some environments.
2051
2052 IF set to a true value (or undefined) then DUMP directives will
2053 operate.
2054
2055 If set to a hashref, the values of the hash can be used to con‐
2056 figure the operation of the DUMP directives. The following are
2057 the values that can be set in this hash.
2058
2059 EntireStash
2060 Default 1. If set to 0, then the DUMP directive will not
2061 print the entire contents of the stash when a DUMP direc‐
2062 tive is called without arguments.
2063
2064 handler
2065 Defaults to an internal coderef. If set to a coderef, the
2066 DUMP directive will pass the arguments to be dumped and
2067 expects a string with the dumped data. This gives complete
2068 control over the dump process.
2069
2070 Note 1: The default handler makes sure that values matching
2071 the private variable regex are not included. If you
2072 install your own handler, you will need to take care of
2073 these variables if you intend for them to not be shown.
2074
2075 Note 2: If you would like the name of the variable to be
2076 dumped, include the string '$VAR1' and the DUMP directive
2077 will interpolate the value. For example, to dump all out‐
2078 put as YAML - you could do the following:
2079
2080 DUMP => {
2081 handler => sub {
2082 require YAML;
2083 return "\$VAR1 =\n".YAML::Dump(shift);
2084 },
2085 }
2086
2087 header
2088 Default 1. Controls whether a header is printed for each
2089 DUMP directive. The header contains the file and line num‐
2090 ber the DUMP directive was called from. If set to 0 the
2091 headers are disabled.
2092
2093 html
2094 Defaults to 1 if $ENV{'REQUEST_METHOD'} is set - 0 other‐
2095 wise. If set to 1, then the output of the DUMP directive
2096 is passed to the html filter and encased in "pre" tags. If
2097 set to 0 no html encoding takes place.
2098
2099 Sortkeys, Useqq, Ident, Pad, etc
2100 Any of the Data::Dumper configuration items may be passed.
2101
2102 END_TAG
2103 Set a string to use as the closing delimiter for TT. Default
2104 is "%]".
2105
2106 ERROR
2107 Used as a fall back when the processing of a template fails.
2108 May either be a single filename that will be used in all cases,
2109 or may be a hashref of options where the keynames represent
2110 error types that will be handled by the filename in their
2111 value. A key named default will be used if no other matching
2112 keyname can be found. The selection process is similar to that
2113 of the TRY/CATCH/THROW directives (see those directives for
2114 more information).
2115
2116 my $t = Template::Alloy->new({
2117 ERROR => 'general/catch_all_errors.html',
2118 });
2119
2120 my $t = Template::Alloy->new({
2121 ERROR => {
2122 default => 'general/catch_all_errors.html',
2123 foo => 'catch_all_general_foo_errors.html',
2124 'foo.bar' => 'catch_foo_bar_errors.html',
2125 },
2126 });
2127
2128 Note that the ERROR handler will only be used for errors during
2129 the processing of the main document. It will not catch errors
2130 that occur in templates found in the PRE_PROCESS, POST_PROCESS,
2131 and WRAPPER configuration items.
2132
2133 ERRORS
2134 Same as the ERROR configuration item. Both may be used inter‐
2135 changably.
2136
2137 EVAL_PERL
2138 Boolean. Default false. If set to a true value, PERL and RAW‐
2139 PERL blocks will be allowed to run. This is a potential secu‐
2140 rity hole, as arbitrary perl can be included in the template.
2141 If Template::Toolkit is installed, a true EVAL_PERL value also
2142 allows the perl and evalperl filters to be used.
2143
2144 FILTERS
2145 Allow for passing in TT style filters.
2146
2147 my $filters = {
2148 filter1 => sub { my $str = shift; $s =~ s/./1/gs; $s },
2149 filter2 => [sub { my $str = shift; $s =~ s/./2/gs; $s }, 0],
2150 filter3 => [sub { my ($context, @args) = @_; return sub { my $s = shift; $s =~ s/./3/gs; $s } }, 1],
2151 };
2152
2153 my $str = q{
2154 [% a = "Hello" %]
2155 1 ([% a ⎪ filter1 %])
2156 2 ([% a ⎪ filter2 %])
2157 3 ([% a ⎪ filter3 %])
2158 };
2159
2160 my $obj = Template::Alloy->new(FILTERS => $filters);
2161 $obj->process(\$str) ⎪⎪ die $obj->error;
2162
2163 Would print:
2164
2165 1 (11111)
2166 2 (22222)
2167 3 (33333)
2168
2169 Filters passed in as an arrayref should contain a coderef and a
2170 value indicating if they are dynamic or static (true meaning
2171 dynamic). The dynamic filters are passed the pseudo context
2172 object and any arguments and should return a coderef that will
2173 be called as the filter. The filter coderef is then passed the
2174 string.
2175
2176 GLOBAL_CACHE
2177 Default 0. If true, documents will be cached in $Tem‐
2178 plate::Alloy::GLOBAL_CACHE. It may also be passed a hashref,
2179 in which case the documents will be cached in the passed
2180 hashref.
2181
2182 The TT, Tmpl, and velocity will automatically cache documents
2183 in the object. The HTML::Template interface uses a new object
2184 each time. Setting the HTML::Template's CACHE configuration is
2185 the same as setting GLOBAL_CACHE.
2186
2187 INCLUDE_PATH
2188 A string or an arrayref or coderef that returns an arrayref
2189 that contains directories to look for files included by pro‐
2190 cessed templates. Defaults to "." (the current directory).
2191
2192 INCLUDE_PATHS
2193 Non-TT item. Same as INCLUDE_PATH but only takes an arrayref.
2194 If not specified then INCLUDE_PATH is turned into an arrayref
2195 and stored in INCLUDE_PATHS. Overrides INCLUDE_PATH.
2196
2197 INTERPOLATE
2198 Boolean. Specifies whether variables in text portions of the
2199 template will be interpolated. For example, the $variable and
2200 ${var.value} would be substituted with the appropriate values
2201 from the variable cache (if INTERPOLATE is on).
2202
2203 [% IF 1 %]The variable $variable had a value ${var.value}[% END %]
2204
2205 LOAD_PERL
2206 Indicates if the USE directive can fall back and try and load a
2207 perl module if the indicated module was not found in the PLUG‐
2208 IN_BASE path. See the USE directive. This configuration has
2209 no bearing on the COMPILE_PERL directive used to indicate using
2210 compiled perl documents.
2211
2212 MAX_EVAL_RECURSE (Alloy only)
2213 Will use $Template::Alloy::MAX_EVAL_RECURSE if not present.
2214 Default is 50. Prevents runaway on the following:
2215
2216 [% f = "[% f⎪eval %]" %][% f⎪eval %]
2217
2218 MAX_MACRO_RECURSE (Alloy only)
2219 Will use $Template::Alloy::MAX_MACRO_RECURSE if not present.
2220 Default is 50. Prevents runaway on the following:
2221
2222 [% MACRO f BLOCK %][% f %][% END %][% f %]
2223
2224 NAMESPACE
2225 No Template::Namespace::Constants support. Hashref of hashrefs
2226 representing constants that will be folded into the template at
2227 compile time.
2228
2229 Template::Alloy->new(NAMESPACE => {constants => {
2230 foo => 'bar',
2231 }});
2232
2233 Is the same as
2234
2235 Template::Alloy->new(CONSTANTS => {
2236 foo => 'bar',
2237 });
2238
2239 Any number of hashes can be added to the NAMESPACE hash.
2240
2241 NEGATIVE_STAT_TTL (Not in TT)
2242 Defaults to STAT_TTL which defaults to $STAT_TTL which defaults
2243 to 1.
2244
2245 Similar to STAT_TTL - but represents the time-to-live seconds
2246 until a document that was not found is checked again against
2247 the system for modifications. Setting this number higher will
2248 allow for fewer file system accesses. Setting it to a negative
2249 number will allow for the file system to be checked every hit.
2250
2251 NO_INCLUDES
2252 Default false. If true, calls to INCLUDE, PROCESS, WRAPPER and
2253 INSERT will fail. This option is also available when using the
2254 process method.
2255
2256 OUTPUT
2257 Alternate way of passing in the output location for processed
2258 templates. If process is not passed an output argument, it
2259 will look for this value.
2260
2261 See the process method for a listing of possible values.
2262
2263 OUTPUT_PATH
2264 Base path for files written out via the process method or via
2265 the redirect and file filters. See the redirect virtual method
2266 and the process method for more information.
2267
2268 PLUGINS
2269 A hashref of mappings of plugin modules.
2270
2271 PLUGINS => {
2272 Iterator => 'Template::Plugin::Iterator',
2273 DBI => 'MyDBI',
2274 },
2275
2276 See the USE directive for more information.
2277
2278 PLUGIN_BASE
2279 Default value is Template::Plugin. The base module namespace
2280 that template plugins will be looked for. See the USE direc‐
2281 tive for more information. May be either a single namespace,
2282 or an arrayref of namespaces.
2283
2284 POST_CHOMP
2285 Set the type of chomping at the ending of a tag. See the sec‐
2286 tion on chomping for more information.
2287
2288 POST_PROCESS
2289 Only available via when using the process interface.
2290
2291 A list of templates to be processed and appended to the content
2292 after the main template. During this processing the "template"
2293 namespace will contain the name of the main file being pro‐
2294 cessed.
2295
2296 This is useful for adding a global footer to all templates.
2297
2298 PRE_CHOMP
2299 Set the type of chomping at the beginning of a tag. See the
2300 section on chomping for more information.
2301
2302 PRE_DEFINE
2303 Same as the VARIABLES configuration item.
2304
2305 PRE_PROCESS
2306 Only available via when using the process interface.
2307
2308 A list of templates to be processed before and pre-pended to
2309 the content before the main template. During this processing
2310 the "template" namespace will contain the name of the main file
2311 being processed.
2312
2313 This is useful for adding a global header to all templates.
2314
2315 PROCESS
2316 Only available via when using the process interface.
2317
2318 Specify a file to use as the template rather than the one
2319 passed in to the ->process method.
2320
2321 RECURSION
2322 Boolean. Default false. Indicates that INCLUDED or PROCESSED
2323 files can refer to each other in a circular manner. Be careful
2324 about recursion.
2325
2326 RELATIVE
2327 Boolean. Default false. If true, allows filenames to be spec‐
2328 ified that are relative to the currently running process.
2329
2330 SEMICOLONS
2331 Boolean. Default fast. If true, then the syntax will require
2332 that semi-colons separate multiple directives in the same tag.
2333 This is useful for keeping the syntax a little more clean as
2334 well as trouble shooting some errors.
2335
2336 SHOW_UNDEFINED_INTERP (Not in TT)
2337 Default false (default true in Velocity). If INTERPOLATE is
2338 true, interpolated dollar variables that return undef will be
2339 removed. With SHOW_UNDEFINED_INTERP set, undef values will
2340 leave the variable there.
2341
2342 [% CONFIG INTERPOLATE => 1 %]
2343 [% SET foo = 1 %][% SET bar %]
2344 ($foo)($bar) ($!foo)($!bar)
2345
2346 Would print:
2347
2348 (1)() (1)()
2349
2350 But the following:
2351
2352 [% CONFIG INTERPOLATE => 1, SHOW_UNDEFINED_INTERP => 1 %]
2353 [% SET foo = 1 %][% SET bar %]
2354 ($foo)($bar) ($!foo)($!bar)
2355
2356 Would print:
2357
2358 (1)($bar) (1)()
2359
2360 Note that you can use an exclamation point directly after the
2361 the dollar to make the variable silent. This is similar to how
2362 Velocity works.
2363
2364 START_TAG
2365 Set a string or regular expression to use as the opening delim‐
2366 iter for TT. Default is "[%". You should be sure that the tag
2367 does not include grouping parens or INTERPOLATE will not func‐
2368 tion properly.
2369
2370 STASH
2371 Template::Alloy manages its own stash of variables. You can
2372 pass a Template::Stash or Template::Stash::XS object, but Tem‐
2373 plate::Alloy will copy all of values out of the object into its
2374 own stash. Template::Alloy won't use any of the methods of the
2375 passed STASH object. The STASH option is only available when
2376 using the process method.
2377
2378 STAT_TTL
2379 Defaults to $STAT_TTL which defaults to 1. Represents time-to-
2380 live seconds until a cached in memory document is compared to
2381 the file system for modifications. Setting this number higher
2382 will allow for fewer file system accesses. Setting it to a
2383 negative number will allow for the file system to be checked
2384 every hit.
2385
2386 SYNTAX (not in TT)
2387 Defaults to "cet". Indicates the syntax that will be used for
2388 parsing included templates or eval'ed strings. You can use the
2389 CONFIG directive to change the SYNTAX on the fly (it will not
2390 affect the syntax of the document currently being parsed).
2391
2392 The syntax may be passed in upper or lower case.
2393
2394 The available choices are:
2395
2396 alloy - Template::Alloy style - the same as TT3
2397 tt3 - Template::Toolkit ver3 - same as Alloy
2398 tt2 - Template::Toolkit ver2 - almost the same as TT3
2399 tt1 - Template::Toolkit ver1 - almost the same as TT2
2400 ht - HTML::Template - same as HTML::Template::Expr without EXPR
2401 hte - HTML::Template::Expr
2402
2403 Passing in a different syntax allows for the process method to
2404 use a non-TT syntax and for the output method to use a non-HT
2405 syntax.
2406
2407 The following is a sample of HTML::Template interface usage
2408 parsing a Template::Toolkit style document.
2409
2410 my $obj = Template::Alloy->new(filename => 'my/template.tt'
2411 syntax => 'cet');
2412 $obj->param(\%swap);
2413 print $obj->output;
2414
2415 The following is a sample of Template::Toolkit interface usage
2416 parsing a HTML::Template::Expr style document.
2417
2418 my $obj = Template::Alloy->new(SYNTAX => 'hte');
2419 $obj->process('my/template.ht', \%swap);
2420
2421 You can use the define_syntax method to add another custom syn‐
2422 tax to the list of available options.
2423
2424 TAG_STYLE
2425 Allow for setting the type of tag delimiters to use for parsing
2426 the TT. See the TAGS directive for a listing of the available
2427 types.
2428
2429 TRIM
2430 Remove leading and trailing whitespace from blocks and tem‐
2431 plates. This operation is performed after all enclosed tem‐
2432 plate tags have been executed.
2433
2434 UNDEFINED_ANY
2435 This is not a TT configuration option. This option expects to
2436 be a code ref that will be called if a variable is undefined
2437 during a call to play_expr. It is passed the variable identity
2438 array as a single argument. This is most similar to the "unde‐
2439 fined" method of Template::Stash. It allows for the
2440 "auto-defining" of a variable for use in the template. It is
2441 suggested that UNDEFINED_GET be used instead as UNDEFINED_ANY
2442 is a little to general in defining variables.
2443
2444 You can also sub class the module and override the unde‐
2445 fined_any method.
2446
2447 UNDEFINED_GET
2448 This is not a TT configuration option. This option expects to
2449 be a code ref that will be called if a variable is undefined
2450 during a call to GET. It is passed the variable identity array
2451 as a single argument. This is more useful than UNDEFINED_ANY
2452 in that it is only called during a GET directive rather than in
2453 embedded expressions (such as [% a ⎪⎪ b ⎪⎪ c %]).
2454
2455 You can also sub class the module and override the unde‐
2456 fined_get method.
2457
2458 V1DOLLAR
2459 This allows for some compatibility with TT1 templates. The
2460 only real behavior change is that [% $foo %] becomes the same
2461 as [% foo %]. The following is a basic table of changes
2462 invoked by using V1DOLLAR.
2463
2464 With V1DOLLAR Equivalent Without V1DOLLAR (Normal default)
2465 "[% foo %]" "[% foo %]"
2466 "[% $foo %]" "[% foo %]"
2467 "[% ${foo} %]" "[% ${foo} %]"
2468 "[% foo.$bar %]" "[% foo.bar %]"
2469 "[% ${foo.bar} %]" "[% ${foo.bar} %]"
2470 "[% ${foo.$bar} %]" "[% ${foo.bar} %]"
2471 "Text: $foo" "Text: $foo"
2472 "Text: ${foo}" "Text: ${foo}"
2473 "Text: ${$foo}" "Text: ${foo}"
2474
2475 V2EQUALS
2476 Default 1 in TT syntaxes, defaults to 0 in HTML::Template syn‐
2477 taxes.
2478
2479 If set to 1 then "==" is an alias for "eq" and "!= is an alias
2480 for "ne".
2481
2482 [% CONFIG V2EQUALS => 1 %][% ('7' == '7.0') ⎪⎪ 0 %]
2483 [% CONFIG V2EQUALS => 0 %][% ('7' == '7.0') ⎪⎪ 0 %]
2484
2485 Prints
2486
2487 0
2488 1
2489
2490 V2PIPE
2491 Restores the behavior of the pipe operator to be compatible
2492 with TT2.
2493
2494 With V2PIPE = 1
2495
2496 [%- BLOCK a %]b is [% b %]
2497 [% END %]
2498 [%- PROCESS a b => 237 ⎪ repeat(2) %]
2499
2500 # output of block "a" with b set to 237 is passed to the repeat(2) filter
2501
2502 b is 237
2503 b is 237
2504
2505 With V2PIPE = 0 (default)
2506
2507 [%- BLOCK a %]b is [% b %]
2508 [% END %]
2509 [% PROCESS a b => 237 ⎪ repeat(2) %]
2510
2511 # b set to 237 repeated twice, and b passed to block "a"
2512
2513 b is 237237
2514
2515 VARIABLES
2516 A hashref of variables to initialize the template stash with.
2517 These variables are available for use in any of the executed
2518 templates. See the section on VARIABLES for the types of
2519 information that can be passed in.
2520
2521 VMETHOD_FUNCTIONS
2522 Defaults to 1. All scalar virtual methods are available as top
2523 level functions as well. This is not true of TT2. In Tem‐
2524 plate::Alloy the following are equivalent:
2525
2526 [% "abc".length %]
2527 [% length("abc") %]
2528
2529 You may set VMETHOD_FUNCTIONS to 0 to disable this behavior.
2530
2531 WRAPPER
2532 Only available via when using the process interface.
2533
2534 Operates similar to the WRAPPER directive. The option can be
2535 given a single filename, or an arrayref of filenames that will
2536 be used to wrap the processed content. If an arrayref is
2537 passed the filenames are processed in reverse order, so that
2538 the first filename specified will end up being on the outside
2539 (surrounding all other wrappers).
2540
2541 my $t = Template::Alloy->new(
2542 WRAPPER => ['my/wrappers/outer.html', 'my/wrappers/inner.html'],
2543 );
2544
2545 Content generated by the PRE_PROCESS and POST_PROCESS will come
2546 before and after (respectively) the content generated by the
2547 WRAPPER configuration item.
2548
2549 See the WRAPPER direcive for more examples of how wrappers are
2550 construted.
2551
2553 The following HTML::Template and HTML::Template::Expr configuration
2554 variables are supported (in HTML::Template documentation order). Note:
2555 for further discussion you can refer to the HT documentation. Many of
2556 the variables mentioned in the TT CONFIGURATION section apply here as
2557 well. Unless noted, these items only apply when using the output
2558 method.
2559
2560 Items may be passed in upper or lower case. All passed items are
2561 resolved to upper case.
2562
2563 These variables should be passed to the "new" constructor.
2564
2565 my $obj = Template::Alloy->new(
2566 type => 'filename',
2567 source => 'my/template.ht',
2568 die_on_bad_params => 1,
2569 loop_context_vars => 1,
2570 global_vars => 1
2571 post_chomp => "=",
2572 pre_chomp => "-",
2573 );
2574
2575 TYPE
2576 Can be one of filename, filehandle, arrayref, or scalarref. Indi‐
2577 cates what type of input is in the "source" configuration item.
2578
2579 SOURCE
2580 Stores where to read the input file. The type is specified in the
2581 "type" configuration item.
2582
2583 FILENAME
2584 Indicates a filename to read the template from. Same as putting
2585 the filename in the "source" item and setting "type" to "filename".
2586
2587 Must be set to enable caching.
2588
2589 FILEHANDLE
2590 Should contain an open filehandle to read the template from. Same
2591 as putting the filehandle in the "source" item and setting "type"
2592 to "filehandle".
2593
2594 Will not be cached.
2595
2596 ARRAYREF
2597 Should contain an arrayref whose values are the lines of the tem‐
2598 plate. Same as putting the arrayref in the "source" item and set‐
2599 ting "type" to "arrayref".
2600
2601 Will not be cached.
2602
2603 SCALARREF
2604 Should contain an reference to a scalar that contains the template.
2605 Same as putting the scalar ref in the "source" item and setting
2606 "type" to "scalarref".
2607
2608 Will not be cached.
2609
2610 CACHE
2611 If set to one, then Alloy will use a global, in-memory document
2612 cache to store compiled templates in between calls. This is gener‐
2613 ally only useful in a mod_perl environment. The document is
2614 checked for a different modification time at each request.
2615
2616 BLIND_CACHE
2617 Same as with cache enabled, but will not check if the document has
2618 been modified.
2619
2620 FILE_CACHE
2621 If set to 1, will cache the compiled document on the file system.
2622 If true, file_cache_dir must be set.
2623
2624 FILE_CACHE_DIR
2625 The directory where to store cached documents when file_cache is
2626 true. This is similar to the TT compile_dir option.
2627
2628 DOUBLE_FILE_CACHE
2629 Uses a combination of file_cache and cache.
2630
2631 PATH
2632 Same as INCLUDE_PATH when using the process method.
2633
2634 ASSOCIATE
2635 May be a single CGI object or an arrayref of objects. The params
2636 from these objects will be added to the params during the output
2637 call.
2638
2639 CASE_SENSITIVE
2640 Allow passed variables set through the param method, or the asso‐
2641 ciate configuration to be used case sensitively. Default is off.
2642 It is highly suggested that this be set to 1.
2643
2644 LOOP_CONTEXT_VARS
2645 Default false. When true, calls to the loop directive will create
2646 the following variables that give information about the current
2647 iteration of the loop:
2648
2649 __first__ - True on first iteration only
2650 __last__ - True on last iteration only
2651 __inner__ - True on any iteration that isn't first or last
2652 __odd__ - True on odd iterations
2653 __counter__ - The iteration count
2654
2655 These variables are also available to LOOPs run under TT syntax if
2656 loop_context_vars is set and if QR_PRIVATE is set to 0.
2657
2658 GLOBAL_VARS.
2659 Default true in HTE mode. Default false in HT. Allows top level
2660 variables to be used in LOOPs. When false, only variables defined
2661 in the current LOOP iteration hashref will be available.
2662
2663 DEFAULT_ESCAPE
2664 Controls the type of escape used on named variables in TMPL_VAR
2665 directives. Can be one of HTML, URL, or JS. The values of
2666 TMPL_VAR directives will be encoded with this type unless they
2667 specify their own type via an ESCAPE attribute.
2668
2669 NO_TT
2670 Default false in 'hte' syntax. Default true in 'ht' syntax. If
2671 true, no extended TT directives will be allowed.
2672
2673 The output method uses 'hte' syntax by default.
2674
2676 The following list of methods are other interesting methods of Alloy
2677 that may be re-implemented by subclasses of Alloy.
2678
2679 "exception"
2680 Creates an exception object blessed into the package listed in Tem‐
2681 plate::Alloy::Exception.
2682
2683 "execute_tree"
2684 Executes a parsed tree (returned from parse_tree)
2685
2686 "play_expr"
2687 Play the parsed expression. Turns a variable identity array into
2688 the parsed variable. This method is also responsible for playing
2689 operators and running virtual methods and filters. The variable
2690 identity array may also contain literal values, or operator iden‐
2691 tity arrays.
2692
2693 "include_filename"
2694 Takes a file path, and resolves it into the full filename using
2695 paths from INCLUDE_PATH or INCLUDE_PATHS.
2696
2697 "_insert"
2698 Resolves the file passed, and then returns its contents.
2699
2700 "list_filters"
2701 Dynamically loads the filters list from Template::Filters when a
2702 filter is used that is not natively implemented in Alloy.
2703
2704 "list_plugins"
2705 Returns an arrayref of modules that are under a base Namespace.
2706
2707 my @modules = @{ $self->list_plugins({base => 'Template::Plugins'}) }:
2708
2709 Provided by the Play role.
2710
2711 "load_template"
2712 Given a filename or a string reference will return a "document"
2713 hashref hash that contains the parsed tree.
2714
2715 my $doc = $self->load_template($file); # errors die
2716
2717 This method handles the in-memory caching of the document.
2718
2719 "load_tree"
2720 Given the "document" hashref, will either load the parsed AST from
2721 file (if configured to do so), or will load the content, parse the
2722 content using the Parse role, and will return the tree. File based
2723 caching of the parsed AST happens here.
2724
2725 "load_perl"
2726 Only used if COMPILE_PERL is true (default is false).
2727
2728 Given the "document" hashref, will either load the compiled perl
2729 from file (if configured to do so), or will load the AST using
2730 "load_tree", will compile a new perl code document using the Com‐
2731 pile role, and will return the perl code. File based caching of
2732 the compiled perl happens here.
2733
2734 "parse_tree"
2735 Parses the passed string ref with the appopriate template syntax.
2736
2737 See Template::Alloy::Parse for more details.
2738
2739 "parse_expr"
2740 Parses the passed string ref for a variable or expression.
2741
2742 See Template::Alloy::Parse for more details.
2743
2744 "parse_args"
2745 See Template::Alloy::Parse for more details.
2746
2747 "set_variable"
2748 Used to set a variable. Expects a variable identity array and the
2749 value to set. It will autovifiy as necessary.
2750
2751 "throw"
2752 Creates an exception object from the arguments and dies.
2753
2754 "undefined_any"
2755 Called during play_expr if a value is returned that is undefined.
2756 This could be used to magically create variables on the fly. This
2757 is similar to Template::Stash::undefined. It is suggested that
2758 undefined_get be used instead. Default behavior returns undef.
2759 You may also pass a coderef via the UNDEFINED_ANY configuration
2760 variable. Also, you can try using the DEBUG => 'undef', configura‐
2761 tion option which will throw an error on undefined variables.
2762
2763 "undefined_get"
2764 Called when a variable is undefined during a GET directive. This
2765 is useful to see if a value that is about to get inserted into the
2766 text is undefined. undefined_any is a little too general for most
2767 cases. Also, you may pass a coderef via the UNDEFINED_GET configu‐
2768 ration variable.
2769
2771 The following is a brief list of other methods used by Alloy. Gener‐
2772 ally, these shouldn't be overwritten by subclasses.
2773
2774 "context"
2775 Used to create a "pseudo" context object that allows for portabil‐
2776 ity of TT plugins, filters, and perl blocks that need a context
2777 object. Uses the Template::Alloy::Context class.
2778
2779 "debug_node"
2780 Used to get debug info on a directive if DEBUG_DIRS is set.
2781
2782 "get_line_number_by_index"
2783 Used to turn string index position into line number
2784
2785 "interpolate_node"
2786 Used for parsing text nodes for dollar variables when interpolate
2787 is on.
2788
2789 "play_operator"
2790 Provided by the Operator role. Allows for playing an operator AST.
2791
2792 See Template::Alloy::Operator for more details.
2793
2794 "apply_precedence"
2795 Provided by the Parse role. Allows for parsed operator array to be
2796 translated to a tree based upon operator precedence.
2797
2798 "_process"
2799 Called by process and the PROCESS, INCLUDE and other directives.
2800
2801 "slurp"
2802 Reads contents of passed filename - throws file exception on error.
2803
2804 "split_paths"
2805 Used to split INCLUDE_PATH or other directives if an arrayref is
2806 not passed.
2807
2808 "_vars"
2809 Return a reference to the current stash of variables. This is cur‐
2810 rently only used by the pseudo context object and may disappear at
2811 some point.
2812
2814 Thanks to Andy Wardley for creating Template::Toolkit.
2815
2816 Thanks to Sam Tregar for creating HTML::Template.
2817
2818 Thanks to David Lowe for creating Text::Tmpl.
2819
2820 Thanks to the Apache Velocity guys.
2821
2822 Thanks to Ben Grimm for a patch to allow passing a parsed document to
2823 the ->process method.
2824
2825 Thanks to David Warring for finding a parse error in HTE syntax.
2826
2828 Paul Seamons <paul at seamons dot com>
2829
2831 This module may be distributed under the same terms as Perl itself.
2832
2833
2834
2835perl v5.8.8 2007-07-24 Template::Alloy(3)