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       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 "$template->service->context()".
241
242   template($name)
243       This method is a simple wrapper around the Template::Context method of
244       the same name.  It returns a compiled template for the source provided
245       as an argument.
246

CONFIGURATION SUMMARY

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

DIRECTIVE SUMMARY

422       The following list gives a short summary of each Template Toolkit
423       directive.  See Template::Manual::Directives for full details.
424
425   GET
426       Evaluate and print a variable or value.
427
428           [%   GET variable %]    # 'GET' keyword is optional
429           [%       variable %]
430           [%       hash.key %]
431           [%         list.n %]
432           [%     code(args) %]
433           [% obj.meth(args) %]
434           [%  "value: $var" %]
435
436   CALL
437       As per GET but without printing result (e.g. call code)
438
439           [%  CALL variable %]
440
441   SET
442       Assign a values to variables.
443
444           [% SET variable = value %]    # 'SET' also optional
445           [%     variable = other_variable
446                  variable = 'literal text @ $100'
447                  variable = "interpolated text: $var"
448                  list     = [ val, val, val, val, ... ]
449                  list     = [ val..val ]
450                  hash     = { var => val, var => val, ... }
451           %]
452
453   DEFAULT
454       Like SET, but variables are only set if currently unset (i.e. have no
455       true value).
456
457           [% DEFAULT variable = value %]
458
459   INSERT
460       Insert a file without any processing performed on the contents.
461
462           [% INSERT legalese.txt %]
463
464   PROCESS
465       Process another template file or block and insert the generated output.
466       Any template BLOCKs or variables defined or updated in the "PROCESS"ed
467       template will thereafter be defined in the calling template.
468
469           [% PROCESS template %]
470           [% PROCESS template  var = val, ... %]
471
472   INCLUDE
473       Similar to "PROCESS", but using a local copy of the current variables.
474       Any template "BLOCK"s or variables defined in the "INCLUDE"d template
475       remain local to it.
476
477           [% INCLUDE template %]
478           [% INCLUDE template  var = val, ... %]
479
480   WRAPPER
481       The content between the "WRAPPER" and correspondng "END" directives is
482       first evaluated, with the output generated being stored in the
483       "content" variable.  The named template is then process as per
484       "INCLUDE".
485
486           [% WRAPPER layout %]
487              Some template markup [% blah %]...
488           [% END %]
489
490       A simple layout template might look something like this:
491
492           Your header here...
493           [% content %]
494           Your footer here...
495
496   BLOCK
497       Define a named template block for INCLUDE, PROCESS and WRAPPER to use.
498
499           [% BLOCK hello %]
500              Hello World
501           [% END %]
502
503           [% INCLUDE hello %]
504
505   FOREACH
506       Repeat the enclosed "FOREACH" ... "END" block for each value in the
507       list.
508
509           [% FOREACH variable IN [ val, val, val ] %]    # either
510           [% FOREACH variable IN list %]                 # or
511              The variable is set to [% variable %]
512           [% END %]
513
514   WHILE
515       The block enclosed between "WHILE" and "END" block is processed while
516       the specified condition is true.
517
518           [% WHILE condition %]
519              content
520           [% END %]
521
522   IF / UNLESS / ELSIF / ELSE
523       The enclosed block is processed if the condition is true / false.
524
525           [% IF condition %]
526              content
527           [% ELSIF condition %]
528            content
529           [% ELSE %]
530            content
531           [% END %]
532
533           [% UNLESS condition %]
534              content
535           [% # ELSIF/ELSE as per IF, above %]
536              content
537           [% END %]
538
539   SWITCH / CASE
540       Multi-way switch/case statement.
541
542           [% SWITCH variable %]
543           [%   CASE val1 %]
544                  content
545           [%   CASE [ val2, val3 ] %]
546                  content
547           [%   CASE %]         # or [% CASE DEFAULT %]
548                  content
549           [% END %]
550
551   MACRO
552       Define a named macro.
553
554           [% MACRO name <directive> %]
555           [% MACRO name(arg1, arg2) <directive> %]
556           ...
557           [% name %]
558           [% name(val1, val2) %]
559
560   FILTER
561       Process enclosed "FILTER" ... "END" block then pipe through a filter.
562
563           [% FILTER name %]                       # either
564           [% FILTER name( params ) %]             # or
565           [% FILTER alias = name( params ) %]     # or
566              content
567           [% END %]
568
569   USE
570       Load a plugin module (see "Template::<Manual::Plugins"), or any regular
571       Perl module when the "LOAD_PERL" option is set.
572
573           [% USE name %]                      # either
574           [% USE name( params ) %]            # or
575           [% USE var = name( params ) %]      # or
576           ...
577           [% name.method %]
578           [% var.method %]
579
580   PERL / RAWPERL
581       Evaluate enclosed blocks as Perl code (requires the "EVAL_PERL" option
582       to be set).
583
584           [% PERL %]
585            # perl code goes here
586            $stash->set('foo', 10);
587            print "set 'foo' to ", $stash->get('foo'), "\n";
588            print $context->include('footer', { var => $val });
589           [% END %]
590
591           [% RAWPERL %]
592              # raw perl code goes here, no magic but fast.
593              $output .= 'some output';
594           [% END %]
595
596   TRY / THROW / CATCH / FINAL
597       Exception handling.
598
599           [% TRY %]
600            content
601              [% THROW type info %]
602           [% CATCH type %]
603            catch content
604              [% error.type %] [% error.info %]
605           [% CATCH %] # or [% CATCH DEFAULT %]
606            content
607           [% FINAL %]
608              this block is always processed
609           [% END %]
610
611   NEXT
612       Jump straight to the next item in a "FOREACH" or "WHILE" loop.
613
614           [% NEXT %]
615
616   LAST
617       Break out of "FOREACH" or "WHILE" loop.
618
619           [% LAST %]
620
621   RETURN
622       Stop processing current template and return to including templates.
623
624           [% RETURN %]
625
626   STOP
627       Stop processing all templates and return to caller.
628
629           [% STOP %]
630
631   TAGS
632       Define new tag style or characters (default: "[%" "%]").
633
634           [% TAGS html %]
635           [% TAGS <!-- --> %]
636
637   COMMENTS
638       Ignored and deleted.
639
640           [% # this is a comment to the end of line
641              foo = 'bar'
642           %]
643
644           [%# placing the '#' immediately inside the directive
645               tag comments out the entire directive
646           %]
647

SOURCE CODE REPOSITORY

649       The source code for the Template Toolkit is held in a public git
650       repository on Github: <https://github.com/abw/Template2>
651

AUTHOR

653       Andy Wardley <abw@wardley.org> <http://wardley.org/>
654

VERSION

656       Template Toolkit version 2.23, released January 2012.
657
659       Copyright (C) 1996-2012 Andy Wardley.  All Rights Reserved.
660
661       This module is free software; you can redistribute it and/or modify it
662       under the same terms as Perl itself.
663
664
665
666perl v5.16.3                      2012-02-07                       Template(3)
Impressum