1Template(3)           User Contributed Perl Documentation          Template(3)
2
3
4

NAME

6       Template - Front-end module to the Template Toolkit
7

SYNOPSIS

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

DESCRIPTION

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

METHODS

49       new(\%config)
50
51       The new() constructor method (implemented by the Template::Base base
52       class) instantiates a new Template object.  A reference to a hash array
53       of configuration items may be passed as a parameter.
54
55           my $tt = Template->new({
56               INCLUDE_PATH => '/usr/local/templates',
57                   EVAL_PERL    => 1,
58           }) ⎪⎪ die $Template::ERROR, "\n";
59
60       A reference to a new Template object is returned, or undef on error.
61       In the latter case, the error message can be retrieved by calling
62       error() as a class method (e.g. "Template->error()") or by examining
63       the $ERROR package variable directly (e.g. $Template::ERROR).
64
65           my $tt = Template->new(\%config)
66               ⎪⎪ die Template->error(), "\n";
67
68           my $tt = Template->new(\%config)
69               ⎪⎪ die $Template::ERROR, "\n";
70
71       For convenience, configuration items may also be specified as a list of
72       items instead of a hash array reference.  These are automatically
73       folded into a hash array by the constructor.
74
75           my $tt = Template->new(INCLUDE_PATH => '/tmp', POST_CHOMP => 1)
76               ⎪⎪ die $Template::ERROR, "\n";
77
78       process($template, \%vars, $output, %options)
79
80       The process() method is called to process a template.  The first param‐
81       eter indicates the input template as one of: a filename relative to
82       INCLUDE_PATH, if defined; a reference to a text string containing the
83       template text; or a file handle reference (e.g. IO::Handle or
84       sub-class) or GLOB (e.g. \*STDIN), from which the template can be read.
85       A reference to a hash array may be passed as the second parameter, con‐
86       taining definitions of template variables.
87
88           $text = "[% INCLUDE header %]\nHello world!\n[% INCLUDE footer %]";
89
90           # filename
91           $tt->process('welcome.tt2')
92               ⎪⎪ die $tt->error(), "\n";
93
94           # text reference
95           $tt->process(\$text)
96               ⎪⎪ die $tt->error(), "\n";
97
98           # GLOB
99           $tt->process(\*DATA)
100               ⎪⎪ die $tt->error(), "\n";
101
102           __END__
103           [% INCLUDE header %]
104           This is a template defined in the __END__ section which is
105           accessible via the DATA "file handle".
106           [% INCLUDE footer %]
107
108       By default, the processed template output is printed to STDOUT.  The
109       process() method then returns 1 to indicate success.  A third parameter
110       may be passed to the process() method to specify a different output
111       location.  This value may be one of: a plain string indicating a file‐
112       name which will be opened (relative to OUTPUT_PATH, if defined) and the
113       output written to; a file GLOB opened ready for output; a reference to
114       a scalar (e.g. a text string) to which output/error is appended; a ref‐
115       erence to a subroutine which is called, passing the output as a parame‐
116       ter; or any object reference which implements a 'print' method (e.g.
117       IO::Handle, Apache::Request, etc.) which will be called, passing the
118       generated output as a parameter.
119
120       Examples:
121
122           # output filename
123           $tt->process('welcome.tt2', $vars, 'welcome.html')
124               ⎪⎪ die $tt->error(), "\n";
125
126           # reference to output subroutine
127           sub myout {
128               my $output = shift;
129                   ...
130           }
131           $tt->process('welcome.tt2', $vars, \&myout)
132               ⎪⎪ die $tt->error(), "\n";
133
134           # reference to output text string
135           my $output = '';
136           $tt->process('welcome.tt2', $vars, \$output)
137               ⎪⎪ die $tt->error(), "\n";
138
139           print "output: $output\n";
140
141       In an Apache/mod_perl handler:
142
143           sub handler {
144               my $req = shift;
145
146               ...
147
148               # direct output to Apache::Request via $req->print($output)
149               $tt->process($file, $vars, $req) ⎪⎪ do {
150                   $req->log_reason($tt->error());
151                   return SERVER_ERROR;
152               };
153
154               return OK;
155           }
156
157       After the optional third output argument can come an optional reference
158       to a hash or a list of (name, value) pairs providing further options
159       for the output.  The only option currently supported is "binmode"
160       which, when set to any true value will ensure that files created (but
161       not any existing file handles passed) will be set to binary mode.
162
163           # either: hash reference of options
164           $tt->process($infile, $vars, $outfile, { binmode => 1 })
165               ⎪⎪ die $tt->error(), "\n";
166
167           # or: list of name, value pairs
168           $tt->process($infile, $vars, $outfile, binmode => 1)
169               ⎪⎪ die $tt->error(), "\n";
170
171       Alternately, the binmode argument can specify a particular IO layer
172       such as ":utf8".
173
174           $tt->process($infile, $vars, $outfile, binmode => ':utf8')
175               ⎪⎪ die $tt->error(), "\n";
176
177       The OUTPUT configuration item can be used to specify a default output
178       location other than \*STDOUT.  The OUTPUT_PATH specifies a directory
179       which should be prefixed to all output locations specified as file‐
180       names.
181
182           my $tt = Template->new({
183               OUTPUT      => sub { ... },       # default
184                   OUTPUT_PATH => '/tmp',
185               ...
186           }) ⎪⎪ die Template->error(), "\n";
187
188           # use default OUTPUT (sub is called)
189           $tt->process('welcome.tt2', $vars)
190               ⎪⎪ die $tt->error(), "\n";
191
192           # write file to '/tmp/welcome.html'
193           $tt->process('welcome.tt2', $vars, 'welcome.html')
194               ⎪⎪ die $tt->error(), "\n";
195
196       The process() method returns 1 on success or undef on error.  The error
197       message generated in the latter case can be retrieved by calling the
198       error() method.  See also "CONFIGURATION SUMMARY" which describes how
199       error handling may be further customised.
200
201       error()
202
203       When called as a class method, it returns the value of the $ERROR pack‐
204       age variable.  Thus, the following are equivalent.
205
206           my $tt = Template->new()
207               ⎪⎪ die Template->error(), "\n";
208
209           my $tt = Template->new()
210               ⎪⎪ die $Template::ERROR, "\n";
211
212       When called as an object method, it returns the value of the internal
213       _ERROR variable, as set by an error condition in a previous call to
214       process().
215
216           $tt->process('welcome.tt2')
217               ⎪⎪ die $tt->error(), "\n";
218
219       Errors are represented in the Template Toolkit by objects of the Tem‐
220       plate::Exception class.  If the process() method returns a false value
221       then the error() method can be called to return an object of this
222       class.  The type() and info() methods can called on the object to
223       retrieve the error type and information string, respectively.  The
224       as_string() method can be called to return a string of the form "$type
225       - $info".  This method is also overloaded onto the stringification
226       operator allowing the object reference itself to be printed to return
227       the formatted error string.
228
229           $tt->process('somefile') ⎪⎪ do {
230               my $error = $tt->error();
231                   print "error type: ", $error->type(), "\n";
232               print "error info: ", $error->info(), "\n";
233                   print $error, "\n";
234           };
235
236       service()
237
238       The Template module delegates most of the effort of processing tem‐
239       plates to an underlying Template::Service object.  This method returns
240       a reference to that object.
241
242       context()
243
244       The Template::Service module uses a core Template::Context object for
245       runtime processing of templates.  This method returns a reference to
246       that object and is equivalent to $template->service->context();
247

CONFIGURATION SUMMARY

249       The following list gives a short summary of each Template Toolkit con‐
250       figuration option.  See Template::Manual::Config for full details.
251
252       Template Style and Parsing Options
253
254       START_TAG, END_TAG
255           Define tokens that indicate start and end of directives (default:
256           '[%' and '%]').
257
258       TAG_STYLE
259           Set START_TAG and END_TAG according to a pre-defined style
260           (default: 'template', as above).
261
262       PRE_CHOMP, POST_CHOMP
263           Remove whitespace before/after directives (default: 0/0).
264
265       TRIM
266           Remove leading and trailing whitespace from template output
267           (default: 0).
268
269       INTERPOLATE
270           Interpolate variables embedded like $this or ${this} (default: 0).
271
272       ANYCASE
273           Allow directive keywords in lower case (default: 0 - UPPER only).
274
275       Template Files and Blocks
276
277       INCLUDE_PATH
278           One or more directories to search for templates.
279
280       DELIMITER
281           Delimiter for separating paths in INCLUDE_PATH (default: ':').
282
283       ABSOLUTE
284           Allow absolute file names, e.g. /foo/bar.html (default: 0).
285
286       RELATIVE
287           Allow relative filenames, e.g. ../foo/bar.html (default: 0).
288
289       DEFAULT
290           Default template to use when another not found.
291
292       BLOCKS
293           Hash array pre-defining template blocks.
294
295       AUTO_RESET
296           Enabled by default causing BLOCK definitions to be reset each time
297           a template is processed.  Disable to allow BLOCK definitions to
298           persist.
299
300       RECURSION
301           Flag to permit recursion into templates (default: 0).
302
303       Template Variables
304
305       VARIABLES, PRE_DEFINE
306           Hash array of variables and values to pre-define in the stash.
307
308       Runtime Processing Options
309
310       EVAL_PERL
311           Flag to indicate if PERL/RAWPERL blocks should be processed
312           (default: 0).
313
314       PRE_PROCESS, POST_PROCESS
315           Name of template(s) to process before/after main template.
316
317       PROCESS
318           Name of template(s) to process instead of main template.
319
320       ERROR
321           Name of error template or reference to hash array mapping error
322           types to templates.
323
324       OUTPUT
325           Default output location or handler.
326
327       OUTPUT_PATH
328           Directory into which output files can be written.
329
330       DEBUG
331           Enable debugging messages.
332
333       Caching and Compiling Options
334
335       CACHE_SIZE
336           Maximum number of compiled templates to cache in memory (default:
337           undef - cache all)
338
339       COMPILE_EXT
340           Filename extension for compiled template files (default: undef -
341           don't compile).
342
343       COMPILE_DIR
344           Root of directory in which compiled template files should be writ‐
345           ten (default: undef - don't compile).
346
347       Plugins and Filters
348
349       PLUGINS
350           Reference to a hash array mapping plugin names to Perl packages.
351
352       PLUGIN_BASE
353           One or more base classes under which plugins may be found.
354
355       LOAD_PERL
356           Flag to indicate regular Perl modules should be loaded if a named
357           plugin can't be found  (default: 0).
358
359       FILTERS
360           Hash array mapping filter names to filter subroutines or factories.
361
362       Compatibility, Customisation and Extension
363
364       V1DOLLAR
365           Backwards compatibility flag enabling version 1.* handling (i.e.
366           ignore it) of leading '$' on variables (default: 0 - '$' indicates
367           interpolation).
368
369       LOAD_TEMPLATES
370           List of template providers.
371
372       LOAD_PLUGINS
373           List of plugin providers.
374
375       LOAD_FILTERS
376           List of filter providers.
377
378       TOLERANT
379           Set providers to tolerate errors as declinations (default: 0).
380
381       SERVICE
382           Reference to a custom service object (default: Template::Service).
383
384       CONTEXT
385           Reference to a custom context object (default: Template::Context).
386
387       STASH
388           Reference to a custom stash object (default: Template::Stash).
389
390       PARSER
391           Reference to a custom parser object (default: Template::Parser).
392
393       GRAMMAR
394           Reference to a custom grammar object (default: Template::Grammar).
395

DIRECTIVE SUMMARY

397       The following list gives a short summary of each Template Toolkit
398       directive.  See Template::Manual::Directives for full details.
399
400       GET Evaluate and print a variable or value.
401
402               [%   GET variable %]    # 'GET' keyword is optional
403
404               [%       variable %]
405               [%       hash.key %]
406               [%         list.n %]
407               [%     code(args) %]
408               [% obj.meth(args) %]
409               [%  "value: $var" %]
410
411       CALL
412           As per GET but without printing result (e.g. call code)
413
414               [%  CALL variable %]
415
416       SET Assign a values to variables.
417
418               [% SET variable = value %]    # 'SET' also optional
419
420               [%     variable = other_variable
421                      variable = 'literal text @ $100'
422                      variable = "interpolated text: $var"
423                      list     = [ val, val, val, val, ... ]
424                      list     = [ val..val ]
425                      hash     = { var => val, var => val, ... }
426               %]
427
428       DEFAULT
429           Like SET above, but variables are only set if currently unset (i.e.
430           have no true value).
431
432               [% DEFAULT variable = value %]
433
434       INSERT
435           Insert a file without any processing performed on the contents.
436
437               [% INSERT legalese.txt %]
438
439       INCLUDE
440           Process another template file or block and include the output.
441           Variables are localised.
442
443               [% INCLUDE template %]
444               [% INCLUDE template  var = val, ... %]
445
446       PROCESS
447           As INCLUDE above, but without localising variables.
448
449               [% PROCESS template %]
450               [% PROCESS template  var = val, ... %]
451
452       WRAPPER
453           Process the enclosed block WRAPPER ... END block then INCLUDE the
454           named template, passing the block output in the 'content' variable.
455
456               [% WRAPPER template %]
457                  content...
458               [% END %]
459
460       BLOCK
461           Define a named template block for subsequent INCLUDE, PROCESS,
462           etc.,
463
464               [% BLOCK template %]
465                  content
466               [% END %]
467
468       FOREACH
469           Repeat the enclosed FOREACH ... END block for each value in the
470           list.
471
472               [% FOREACH variable = [ val, val, val ] %]    # either
473               [% FOREACH variable = list %]                 # or
474               [% FOREACH list %]                            # or
475                  content...
476                  [% variable %]
477               [% END %]
478
479       WHILE
480           Enclosed WHILE ... END block is processed while condition is true.
481
482               [% WHILE condition %]
483                  content
484               [% END %]
485
486       IF / UNLESS / ELSIF / ELSE
487           Enclosed block is processed if the condition is true / false.
488
489               [% IF condition %]
490                  content
491               [% ELSIF condition %]
492                    content
493               [% ELSE %]
494                    content
495               [% END %]
496
497               [% UNLESS condition %]
498                  content
499               [% # ELSIF/ELSE as per IF, above %]
500                  content
501               [% END %]
502
503       SWITCH / CASE
504           Multi-way switch/case statement.
505
506               [% SWITCH variable %]
507               [% CASE val1 %]
508                  content
509               [% CASE [ val2, val3 ] %]
510                  content
511               [% CASE %]         # or [% CASE DEFAULT %]
512                  content
513               [% END %]
514
515       MACRO
516           Define a named macro.
517
518               [% MACRO name <directive> %]
519               [% MACRO name(arg1, arg2) <directive> %]
520               ...
521               [% name %]
522               [% name(val1, val2) %]
523
524       FILTER
525           Process enclosed FILTER ... END block then pipe through a filter.
526
527               [% FILTER name %]                       # either
528               [% FILTER name( params ) %]             # or
529               [% FILTER alias = name( params ) %]     # or
530                  content
531               [% END %]
532
533       USE Load a "plugin" module, or any regular Perl module if LOAD_PERL
534           option is set.
535
536               [% USE name %]                          # either
537               [% USE name( params ) %]                # or
538               [% USE var = name( params ) %]          # or
539               ...
540               [% name.method %]
541               [% var.method %]
542
543       PERL / RAWPERL
544           Evaluate enclosed blocks as Perl code (requires EVAL_PERL option to
545           be set).
546
547               [% PERL %]
548                    # perl code goes here
549                    $stash->set('foo', 10);
550                    print "set 'foo' to ", $stash->get('foo'), "\n";
551                    print $context->include('footer', { var => $val });
552               [% END %]
553
554               [% RAWPERL %]
555                  # raw perl code goes here, no magic but fast.
556                  $output .= 'some output';
557               [% END %]
558
559       TRY / THROW / CATCH / FINAL
560           Exception handling.
561
562               [% TRY %]
563                    content
564                  [% THROW type info %]
565               [% CATCH type %]
566                    catch content
567                  [% error.type %] [% error.info %]
568               [% CATCH %] # or [% CATCH DEFAULT %]
569                    content
570               [% FINAL %]
571                  this block is always processed
572               [% END %]
573
574       NEXT
575           Jump straight to the next item in a FOREACH/WHILE loop.
576
577               [% NEXT %]
578
579       LAST
580           Break out of FOREACH/WHILE loop.
581
582               [% LAST %]
583
584       RETURN
585           Stop processing current template and return to including templates.
586
587               [% RETURN %]
588
589       STOP
590           Stop processing all templates and return to caller.
591
592               [% STOP %]
593
594       TAGS
595           Define new tag style or characters (default: [% %]).
596
597               [% TAGS html %]
598               [% TAGS <!-- --> %]
599
600       COMMENTS
601           Ignored and deleted.
602
603               [% # this is a comment to the end of line
604                  foo = 'bar'
605               %]
606
607               [%# placing the '#' immediately inside the directive
608                   tag comments out the entire directive
609               %]
610

AUTHOR

612       Andy Wardley <abw@wardley.org>
613
614       <http://wardley.org/http://wardley.org/>
615

VERSION

617       Template Toolkit version 2.18, released on 09 February 2007.
618
620         Copyright (C) 1996-2007 Andy Wardley.  All Rights Reserved.
621
622       This module is free software; you can redistribute it and/or modify it
623       under the same terms as Perl itself.
624
625
626
627perl v5.8.8                       2007-02-09                       Template(3)
Impressum