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

DIRECTIVE SUMMARY

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

SOURCE CODE REPOSITORY

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

AUTHOR

657       Andy Wardley <abw@wardley.org> <http://wardley.org/>
658

VERSION

660       Template Toolkit version 2.26, released January 2014.
661
663       Copyright (C) 1996-2014 Andy Wardley.  All Rights Reserved.
664
665       This module is free software; you can redistribute it and/or modify it
666       under the same terms as Perl itself.
667
668
669
670perl v5.28.0                      2016-12-13                       Template(3)
Impressum