1Template(3) User Contributed Perl Documentation Template(3)
2
3
4
6 Template - Front-end module to the Template Toolkit
7
9 use Template;
10
11 # some useful options (see below for full list)
12 my $config = {
13 INCLUDE_PATH => '/search/path', # or list ref
14 INTERPOLATE => 1, # expand "$var" in plain text
15 POST_CHOMP => 1, # cleanup whitespace
16 PRE_PROCESS => 'header', # prefix each template
17 EVAL_PERL => 1, # evaluate Perl code blocks
18 };
19
20 # create Template object
21 my $template = Template->new($config);
22
23 # define template variables for replacement
24 my $vars = {
25 var1 => $value,
26 var2 => \%hash,
27 var3 => \@list,
28 var4 => \&code,
29 var5 => $object,
30 };
31
32 # specify input filename, or file handle, text reference, etc.
33 my $input = 'myfile.html';
34
35 # process input template, substituting variables
36 $template->process($input, $vars)
37 || die $template->error();
38
40 This documentation describes the Template module which is the direct
41 Perl interface into the Template Toolkit. It covers the use of the
42 module and gives a brief summary of configuration options and template
43 directives. Please see Template::Manual for the complete reference
44 manual which goes into much greater depth about the features and use of
45 the Template Toolkit. The Template::Tutorial is also available as an
46 introductory guide to using the Template Toolkit.
47
49 new(\%config)
50 The "new()" constructor method (implemented by the Template::Base base
51 class) instantiates a new "Template" object. A reference to a hash
52 array of configuration items may be passed as a parameter.
53
54 my $tt = Template->new({
55 INCLUDE_PATH => '/usr/local/templates',
56 EVAL_PERL => 1,
57 }) || die $Template::ERROR, "\n";
58
59 A reference to a new "Template" object is returned, or undef on error.
60 In the latter case, the error message can be retrieved by calling
61 error() as a class method or by examining the $Template::ERROR package
62 variable directly.
63
64 my $tt = Template->new(\%config)
65 || die Template->error(), "\n";
66
67 my $tt = Template->new(\%config)
68 || die $Template::ERROR, "\n";
69
70 For convenience, configuration items may also be specified as a list of
71 items instead of a hash array reference. These are automatically
72 folded into a hash array by the constructor.
73
74 my $tt = Template->new(INCLUDE_PATH => '/tmp', POST_CHOMP => 1)
75 || die $Template::ERROR, "\n";
76
77 process($template, \%vars, $output, %options)
78 The "process()" method is called to process a template. The first
79 parameter indicates the input template as one of: a filename relative
80 to "INCLUDE_PATH", if defined; a reference to a text string containing
81 the template text; or a file handle reference (e.g. "IO::Handle" or
82 sub-class) or "GLOB" (e.g. "\*STDIN"), from which the template can be
83 read. A reference to a hash array may be passed as the second
84 parameter, containing definitions of template variables.
85
86 # filename
87 $tt->process('welcome.tt2')
88 || die $tt->error(), "\n";
89
90 # text reference
91 $text = "[% INCLUDE header %]\nHello world!\n[% INCLUDE footer %]";
92 $tt->process(\$text)
93 || die $tt->error(), "\n";
94
95 # file handle (GLOB)
96 $tt->process(\*DATA)
97 || die $tt->error(), "\n";
98
99 __END__
100 [% INCLUDE header %]
101 This is a template defined in the __END__ section which is
102 accessible via the DATA "file handle".
103 [% INCLUDE footer %]
104
105 By default, the processed template output is printed to "STDOUT". The
106 "process()" method then returns 1 to indicate success. A third
107 parameter may be passed to the "process()" method to specify a
108 different output location. This value may be one of: a plain string
109 indicating a filename which will be opened (relative to "OUTPUT_PATH",
110 if defined) and the output written to; a file GLOB opened ready for
111 output; a reference to a scalar (e.g. a text string) to which
112 output/error is appended; a reference to a subroutine which is called,
113 passing the output as a parameter; or any object reference which
114 implements a "print()" method (e.g. "IO::Handle", "Apache::Request",
115 etc.) which will be called, passing the generated output as a
116 parameter.
117
118 Examples:
119
120 # output filename
121 $tt->process('welcome.tt2', $vars, 'welcome.html')
122 || die $tt->error(), "\n";
123
124 # reference to output subroutine
125 sub myout {
126 my $output = shift;
127 ...
128 }
129 $tt->process('welcome.tt2', $vars, \&myout)
130 || die $tt->error(), "\n";
131
132 # reference to output text string
133 my $output = '';
134 $tt->process('welcome.tt2', $vars, \$output)
135 || die $tt->error(), "\n";
136
137 print "output: $output\n";
138
139 In an Apache/mod_perl handler:
140
141 sub handler {
142 my $req = shift;
143
144 # ...your code here...
145
146 # direct output to Apache::Request via $req->print($output)
147 $tt->process($file, $vars, $req) || do {
148 $req->log_reason($tt->error());
149 return SERVER_ERROR;
150 };
151 return OK;
152 }
153
154 After the optional third output argument can come an optional reference
155 to a hash or a list of "(name, value)" pairs providing further options
156 for the output. The only option currently supported is "binmode"
157 which, when set to any true value will ensure that files created (but
158 not any existing file handles passed) will be set to binary mode.
159
160 # either: hash reference of options
161 $tt->process($infile, $vars, $outfile, { binmode => 1 })
162 || die $tt->error(), "\n";
163
164 # or: list of name, value pairs
165 $tt->process($infile, $vars, $outfile, binmode => 1)
166 || die $tt->error(), "\n";
167
168 Alternately, the "binmode" argument can specify a particular IO layer
169 such as ":utf8".
170
171 $tt->process($infile, $vars, $outfile, binmode => ':utf8')
172 || die $tt->error(), "\n";
173
174 The "OUTPUT" configuration item can be used to specify a default output
175 location other than "\*STDOUT". The "OUTPUT_PATH" specifies a
176 directory which should be prefixed to all output locations specified as
177 filenames.
178
179 my $tt = Template->new({
180 OUTPUT => sub { ... }, # default
181 OUTPUT_PATH => '/tmp',
182 ...
183 }) || die Template->error(), "\n";
184
185 # use default OUTPUT (sub is called)
186 $tt->process('welcome.tt2', $vars)
187 || die $tt->error(), "\n";
188
189 # write file to '/tmp/welcome.html'
190 $tt->process('welcome.tt2', $vars, 'welcome.html')
191 || die $tt->error(), "\n";
192
193 The "process()" method returns 1 on success or "undef" on error. The
194 error message generated in the latter case can be retrieved by calling
195 the error() method. See also "CONFIGURATION SUMMARY" which describes
196 how error handling may be further customised.
197
198 error()
199 When called as a class method, it returns the value of the $ERROR
200 package variable. Thus, the following are equivalent.
201
202 my $tt = Template->new()
203 || die Template->error(), "\n";
204
205 my $tt = Template->new()
206 || die $Template::ERROR, "\n";
207
208 When called as an object method, it returns the value of the internal
209 "_ERROR" variable, as set by an error condition in a previous call to
210 process().
211
212 $tt->process('welcome.tt2')
213 || die $tt->error(), "\n";
214
215 Errors are represented in the Template Toolkit by objects of the
216 Template::Exception class. If the process() method returns a false
217 value then the "error()" method can be called to return an object of
218 this class. The type() and info() methods can called on the object to
219 retrieve the error type and information string, respectively. The
220 as_string() method can be called to return a string of the form "$type
221 - $info". This method is also overloaded onto the stringification
222 operator allowing the object reference itself to be printed to return
223 the formatted error string.
224
225 $tt->process('somefile') || do {
226 my $error = $tt->error();
227 print "error type: ", $error->type(), "\n";
228 print "error info: ", $error->info(), "\n";
229 print $error, "\n";
230 };
231
232 service()
233 The "Template" module delegates most of the effort of processing
234 templates to an underlying Template::Service object. This method
235 returns a reference to that object.
236
237 context()
238 The Template::Service module uses a core Template::Context object for
239 runtime processing of templates. This method returns a reference to
240 that object and is equivalent to
241 "$template-E<gt>service-E<gt>context()".
242
244 The following list gives a short summary of each Template Toolkit
245 configuration option. See Template::Manual::Config for full details.
246
247 Template Style and Parsing Options
248 START_TAG, END_TAG
249
250 Define tokens that indicate start and end of directives (default:
251 '"[%"' and '"%]"').
252
253 TAG_STYLE
254
255 Set "START_TAG" and "END_TAG" according to a pre-defined style
256 (default: '"template"', as above).
257
258 PRE_CHOMP, POST_CHOMP
259
260 Removes whitespace before/after directives (default: 0/0).
261
262 TRIM
263
264 Remove leading and trailing whitespace from template output (default:
265 0).
266
267 INTERPOLATE
268
269 Interpolate variables embedded like $this or "${this}" (default: 0).
270
271 ANYCASE
272
273 Allow directive keywords in lower case (default: 0 - UPPER only).
274
275 Template Files and Blocks
276 INCLUDE_PATH
277
278 One or more directories to search for templates.
279
280 DELIMITER
281
282 Delimiter for separating paths in "INCLUDE_PATH" (default: '":"').
283
284 ABSOLUTE
285
286 Allow absolute file names, e.g. "/foo/bar.html" (default: 0).
287
288 RELATIVE
289
290 Allow relative filenames, e.g. "../foo/bar.html" (default: 0).
291
292 DEFAULT
293
294 Default template to use when another not found.
295
296 BLOCKS
297
298 Hash array pre-defining template blocks.
299
300 AUTO_RESET
301
302 Enabled by default causing "BLOCK" definitions to be reset each time a
303 template is processed. Disable to allow "BLOCK" definitions to
304 persist.
305
306 RECURSION
307
308 Flag to permit recursion into templates (default: 0).
309
310 Template Variables
311 VARIABLES
312
313 Hash array of variables and values to pre-define in the stash.
314
315 Runtime Processing Options
316 EVAL_PERL
317
318 Flag to indicate if "PERL"/"RAWPERL" blocks should be processed
319 (default: 0).
320
321 PRE_PROCESS, POST_PROCESS
322
323 Name of template(s) to process before/after main template.
324
325 PROCESS
326
327 Name of template(s) to process instead of main template.
328
329 ERROR
330
331 Name of error template or reference to hash array mapping error types
332 to templates.
333
334 OUTPUT
335
336 Default output location or handler.
337
338 OUTPUT_PATH
339
340 Directory into which output files can be written.
341
342 DEBUG
343
344 Enable debugging messages.
345
346 Caching and Compiling Options
347 CACHE_SIZE
348
349 Maximum number of compiled templates to cache in memory (default: undef
350 - cache all)
351
352 COMPILE_EXT
353
354 Filename extension for compiled template files (default: undef - don't
355 compile).
356
357 COMPILE_DIR
358
359 Root of directory in which compiled template files should be written
360 (default: undef - don't compile).
361
362 Plugins and Filters
363 PLUGINS
364
365 Reference to a hash array mapping plugin names to Perl packages.
366
367 PLUGIN_BASE
368
369 One or more base classes under which plugins may be found.
370
371 LOAD_PERL
372
373 Flag to indicate regular Perl modules should be loaded if a named
374 plugin can't be found (default: 0).
375
376 FILTERS
377
378 Hash array mapping filter names to filter subroutines or factories.
379
380 Customisation and Extension
381 LOAD_TEMPLATES
382
383 List of template providers.
384
385 LOAD_PLUGINS
386
387 List of plugin providers.
388
389 LOAD_FILTERS
390
391 List of filter providers.
392
393 TOLERANT
394
395 Set providers to tolerate errors as declinations (default: 0).
396
397 SERVICE
398
399 Reference to a custom service object (default: Template::Service).
400
401 CONTEXT
402
403 Reference to a custom context object (default: Template::Context).
404
405 STASH
406
407 Reference to a custom stash object (default: Template::Stash).
408
409 PARSER
410
411 Reference to a custom parser object (default: Template::Parser).
412
413 GRAMMAR
414
415 Reference to a custom grammar object (default: Template::Grammar).
416
418 The following list gives a short summary of each Template Toolkit
419 directive. See Template::Manual::Directives for full details.
420
421 GET
422 Evaluate and print a variable or value.
423
424 [% GET variable %] # 'GET' keyword is optional
425 [% variable %]
426 [% hash.key %]
427 [% list.n %]
428 [% code(args) %]
429 [% obj.meth(args) %]
430 [% "value: $var" %]
431
432 CALL
433 As per GET but without printing result (e.g. call code)
434
435 [% CALL variable %]
436
437 SET
438 Assign a values to variables.
439
440 [% SET variable = value %] # 'SET' also optional
441 [% variable = other_variable
442 variable = 'literal text @ $100'
443 variable = "interpolated text: $var"
444 list = [ val, val, val, val, ... ]
445 list = [ val..val ]
446 hash = { var => val, var => val, ... }
447 %]
448
449 DEFAULT
450 Like SET, but variables are only set if currently unset (i.e. have no
451 true value).
452
453 [% DEFAULT variable = value %]
454
455 INSERT
456 Insert a file without any processing performed on the contents.
457
458 [% INSERT legalese.txt %]
459
460 PROCESS
461 Process another template file or block and insert the generated output.
462 Any template BLOCKs or variables defined or updated in the "PROCESS"ed
463 template will thereafter be defined in the calling template.
464
465 [% PROCESS template %]
466 [% PROCESS template var = val, ... %]
467
468 INCLUDE
469 Similar to "PROCESS", but using a local copy of the current variables.
470 Any template "BLOCK"s or variables defined in the "INCLUDE"d template
471 remain local to it.
472
473 [% INCLUDE template %]
474 [% INCLUDE template var = val, ... %]
475
476 WRAPPER
477 The content between the "WRAPPER" and correspondng "END" directives is
478 first evaluated, with the output generated being stored in the
479 "content" variable. The named template is then process as per
480 "INCLUDE".
481
482 [% WRAPPER layout %]
483 Some template markup [% blah %]...
484 [% END %]
485
486 A simple layout template might look something like this:
487
488 Your header here...
489 [% content %]
490 Your footer here...
491
492 BLOCK
493 Define a named template block for INCLUDE, PROCESS and WRAPPER to use.
494
495 [% BLOCK hello %]
496 Hello World
497 [% END %]
498
499 [% INCLUDE hello %]
500
501 FOREACH
502 Repeat the enclosed "FOREACH" ... "END" block for each value in the
503 list.
504
505 [% FOREACH variable IN [ val, val, val ] %] # either
506 [% FOREACH variable IN list %] # or
507 The variable is set to [% variable %]
508 [% END %]
509
510 WHILE
511 The block enclosed between "WHILE" and "END" block is processed while
512 the specified condition is true.
513
514 [% WHILE condition %]
515 content
516 [% END %]
517
518 IF / UNLESS / ELSIF / ELSE
519 The enclosed block is processed if the condition is true / false.
520
521 [% IF condition %]
522 content
523 [% ELSIF condition %]
524 content
525 [% ELSE %]
526 content
527 [% END %]
528
529 [% UNLESS condition %]
530 content
531 [% # ELSIF/ELSE as per IF, above %]
532 content
533 [% END %]
534
535 SWITCH / CASE
536 Multi-way switch/case statement.
537
538 [% SWITCH variable %]
539 [% CASE val1 %]
540 content
541 [% CASE [ val2, val3 ] %]
542 content
543 [% CASE %] # or [% CASE DEFAULT %]
544 content
545 [% END %]
546
547 MACRO
548 Define a named macro.
549
550 [% MACRO name <directive> %]
551 [% MACRO name(arg1, arg2) <directive> %]
552 ...
553 [% name %]
554 [% name(val1, val2) %]
555
556 FILTER
557 Process enclosed "FILTER" ... "END" block then pipe through a filter.
558
559 [% FILTER name %] # either
560 [% FILTER name( params ) %] # or
561 [% FILTER alias = name( params ) %] # or
562 content
563 [% END %]
564
565 USE
566 Load a plugin module (see "Template::<Manual::Plugins"), or any regular
567 Perl module when the "LOAD_PERL" option is set.
568
569 [% USE name %] # either
570 [% USE name( params ) %] # or
571 [% USE var = name( params ) %] # or
572 ...
573 [% name.method %]
574 [% var.method %]
575
576 PERL / RAWPERL
577 Evaluate enclosed blocks as Perl code (requires the "EVAL_PERL" option
578 to be set).
579
580 [% PERL %]
581 # perl code goes here
582 $stash->set('foo', 10);
583 print "set 'foo' to ", $stash->get('foo'), "\n";
584 print $context->include('footer', { var => $val });
585 [% END %]
586
587 [% RAWPERL %]
588 # raw perl code goes here, no magic but fast.
589 $output .= 'some output';
590 [% END %]
591
592 TRY / THROW / CATCH / FINAL
593 Exception handling.
594
595 [% TRY %]
596 content
597 [% THROW type info %]
598 [% CATCH type %]
599 catch content
600 [% error.type %] [% error.info %]
601 [% CATCH %] # or [% CATCH DEFAULT %]
602 content
603 [% FINAL %]
604 this block is always processed
605 [% END %]
606
607 NEXT
608 Jump straight to the next item in a "FOREACH" or "WHILE" loop.
609
610 [% NEXT %]
611
612 LAST
613 Break out of "FOREACH" or "WHILE" loop.
614
615 [% LAST %]
616
617 RETURN
618 Stop processing current template and return to including templates.
619
620 [% RETURN %]
621
622 STOP
623 Stop processing all templates and return to caller.
624
625 [% STOP %]
626
627 TAGS
628 Define new tag style or characters (default: "[%" "%]").
629
630 [% TAGS html %]
631 [% TAGS <!-- --> %]
632
633 COMMENTS
634 Ignored and deleted.
635
636 [% # this is a comment to the end of line
637 foo = 'bar'
638 %]
639
640 [%# placing the '#' immediately inside the directive
641 tag comments out the entire directive
642 %]
643
645 Andy Wardley <abw@wardley.org> <http://wardley.org/>
646
648 Template Toolkit version 2.20_1, released April 2009.
649
651 Copyright (C) 1996-2009 Andy Wardley. All Rights Reserved.
652
653 This module is free software; you can redistribute it and/or modify it
654 under the same terms as Perl itself.
655
656
657
658perl v5.10.1 2009-07-21 Template(3)