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