1 #============================================================= -*-perl-*-
6 # Module implementing a simple, user-oriented front-end to the Template
10 # Andy Wardley <abw@wardley.org>
13 # Copyright (C) 1996-2009 Andy Wardley. All Rights Reserved.
15 # This module is free software; you can redistribute it and/or
16 # modify it under the same terms as Perl itself.
18 #========================================================================
25 use base 'Template::Base';
28 use Template::Constants;
29 use Template::Provider;
30 use Template::Service;
33 use Scalar::Util qw(blessed);
35 our $VERSION = '2.22';
38 our $BINMODE = 0 unless defined $BINMODE;
41 # preload all modules if we're running under mod_perl
42 Template::Config->preload() if $ENV{ MOD_PERL };
45 #------------------------------------------------------------------------
46 # process($input, \%replace, $output)
48 # Main entry point for the Template Toolkit. The Template module
49 # delegates most of the processing effort to the underlying SERVICE
50 # object, an instance of the Template::Service class.
51 #------------------------------------------------------------------------
54 my ($self, $template, $vars, $outstream, @opts) = @_;
56 my $options = (@opts == 1) && ref($opts[0]) eq 'HASH'
57 ? shift(@opts) : { @opts };
59 $options->{ binmode } = $BINMODE
60 unless defined $options->{ binmode };
62 # we're using this for testing in t/output.t and t/filter.t so
63 # don't remove it if you don't want tests to fail...
64 $self->DEBUG("set binmode\n") if $DEBUG && $options->{ binmode };
66 $output = $self->{ SERVICE }->process($template, $vars);
68 if (defined $output) {
69 $outstream ||= $self->{ OUTPUT };
70 unless (ref $outstream) {
71 my $outpath = $self->{ OUTPUT_PATH };
72 $outstream = "$outpath/$outstream" if $outpath;
75 # send processed template to output stream, checking for error
76 return ($self->error($error))
77 if ($error = &_output($outstream, \$output, $options));
82 return $self->error($self->{ SERVICE }->error);
87 #------------------------------------------------------------------------
90 # Returns a reference to the the internal SERVICE object which handles
91 # all requests for this Template object
92 #------------------------------------------------------------------------
96 return $self->{ SERVICE };
100 #------------------------------------------------------------------------
103 # Returns a reference to the the CONTEXT object withint the SERVICE
105 #------------------------------------------------------------------------
109 return $self->{ SERVICE }->{ CONTEXT };
113 #========================================================================
114 # -- PRIVATE METHODS --
115 #========================================================================
117 #------------------------------------------------------------------------
119 #------------------------------------------------------------------------
121 my ($self, $config) = @_;
123 # convert any textual DEBUG args to numerical form
124 my $debug = $config->{ DEBUG };
125 $config->{ DEBUG } = Template::Constants::debug_flags($self, $debug)
126 || return if defined $debug && $debug !~ /^\d+$/;
128 # prepare a namespace handler for any CONSTANTS definition
129 if (my $constants = $config->{ CONSTANTS }) {
130 my $ns = $config->{ NAMESPACE } ||= { };
131 my $cns = $config->{ CONSTANTS_NAMESPACE } || 'constants';
132 $constants = Template::Config->constants($constants)
133 || return $self->error(Template::Config->error);
134 $ns->{ $cns } = $constants;
137 $self->{ SERVICE } = $config->{ SERVICE }
138 || Template::Config->service($config)
139 || return $self->error(Template::Config->error);
141 $self->{ OUTPUT } = $config->{ OUTPUT } || \*STDOUT;
142 $self->{ OUTPUT_PATH } = $config->{ OUTPUT_PATH };
148 #------------------------------------------------------------------------
149 # _output($where, $text)
150 #------------------------------------------------------------------------
153 my ($where, $textref, $options) = @_;
157 # call a CODE reference
158 if (($reftype = ref($where)) eq 'CODE') {
161 # print to a glob (such as \*STDOUT)
162 elsif ($reftype eq 'GLOB') {
163 print $where $$textref;
165 # append output to a SCALAR ref
166 elsif ($reftype eq 'SCALAR') {
167 $$where .= $$textref;
169 # push onto ARRAY ref
170 elsif ($reftype eq 'ARRAY') {
171 push @$where, $$textref;
173 # call the print() method on an object that implements the method
174 # (e.g. IO::Handle, Apache::Request, etc)
175 elsif (blessed($where) && $where->can('print')) {
176 $where->print($$textref);
178 # a simple string is taken as a filename
181 # make destination directory if it doesn't exist
182 my $dir = dirname($where);
183 eval { mkpath($dir) unless -d $dir; };
185 # strip file name and line number from error raised by die()
186 ($error = $@) =~ s/ at \S+ line \d+\n?$//;
188 elsif (open(FP, ">$where")) {
189 # binmode option can be 1 or a specific layer, e.g. :utf8
190 my $bm = $options->{ binmode };
191 if ($bm && $bm eq 1) {
201 $error = "$where: $!";
204 # give up, we've done our best
206 $error = "output_handler() cannot determine target type ($where)\n";
219 Template - Front-end module to the Template Toolkit
225 # some useful options (see below for full list)
227 INCLUDE_PATH => '/search/path', # or list ref
228 INTERPOLATE => 1, # expand "$var" in plain text
229 POST_CHOMP => 1, # cleanup whitespace
230 PRE_PROCESS => 'header', # prefix each template
231 EVAL_PERL => 1, # evaluate Perl code blocks
234 # create Template object
235 my $template = Template->new($config);
237 # define template variables for replacement
246 # specify input filename, or file handle, text reference, etc.
247 my $input = 'myfile.html';
249 # process input template, substituting variables
250 $template->process($input, $vars)
251 || die $template->error();
255 This documentation describes the Template module which is the direct
256 Perl interface into the Template Toolkit. It covers the use of the
257 module and gives a brief summary of configuration options and template
258 directives. Please see L<Template::Manual> for the complete reference
259 manual which goes into much greater depth about the features and use
260 of the Template Toolkit. The L<Template::Tutorial> is also available
261 as an introductory guide to using the Template Toolkit.
267 The C<new()> constructor method (implemented by the
268 L<Template::Base|Template::Base#new()> base class) instantiates a new
269 C<Template> object. A reference to a hash array of configuration items may be
270 passed as a parameter.
272 my $tt = Template->new({
273 INCLUDE_PATH => '/usr/local/templates',
275 }) || die $Template::ERROR, "\n";
277 A reference to a new C<Template> object is returned, or undef on error. In the
278 latter case, the error message can be retrieved by calling L<error()> as a
279 class method or by examining the C<$Template::ERROR> package variable
282 my $tt = Template->new(\%config)
283 || die Template->error(), "\n";
285 my $tt = Template->new(\%config)
286 || die $Template::ERROR, "\n";
288 For convenience, configuration items may also be specified as a list
289 of items instead of a hash array reference. These are automatically
290 folded into a hash array by the constructor.
292 my $tt = Template->new(INCLUDE_PATH => '/tmp', POST_CHOMP => 1)
293 || die $Template::ERROR, "\n";
295 =head2 process($template, \%vars, $output, %options)
297 The C<process()> method is called to process a template. The first parameter
298 indicates the input template as one of: a filename relative to
299 C<INCLUDE_PATH>, if defined; a reference to a text string containing the
300 template text; or a file handle reference (e.g. C<IO::Handle> or sub-class) or
301 C<GLOB> (e.g. C<\*STDIN>), from which the template can be read. A reference to
302 a hash array may be passed as the second parameter, containing definitions of
306 $tt->process('welcome.tt2')
307 || die $tt->error(), "\n";
310 $text = "[% INCLUDE header %]\nHello world!\n[% INCLUDE footer %]";
312 || die $tt->error(), "\n";
316 || die $tt->error(), "\n";
320 This is a template defined in the __END__ section which is
321 accessible via the DATA "file handle".
324 By default, the processed template output is printed to C<STDOUT>. The
325 C<process()> method then returns C<1> to indicate success. A third parameter
326 may be passed to the C<process()> method to specify a different output location.
327 This value may be one of: a plain string indicating a filename which will be
328 opened (relative to C<OUTPUT_PATH>, if defined) and the output written to; a file
329 GLOB opened ready for output; a reference to a scalar (e.g. a text string) to
330 which output/error is appended; a reference to a subroutine which is called,
331 passing the output as a parameter; or any object reference which implements a
332 C<print()> method (e.g. C<IO::Handle>, C<Apache::Request>, etc.) which will be called,
333 passing the generated output as a parameter.
338 $tt->process('welcome.tt2', $vars, 'welcome.html')
339 || die $tt->error(), "\n";
341 # reference to output subroutine
346 $tt->process('welcome.tt2', $vars, \&myout)
347 || die $tt->error(), "\n";
349 # reference to output text string
351 $tt->process('welcome.tt2', $vars, \$output)
352 || die $tt->error(), "\n";
354 print "output: $output\n";
356 In an Apache/mod_perl handler:
361 # ...your code here...
363 # direct output to Apache::Request via $req->print($output)
364 $tt->process($file, $vars, $req) || do {
365 $req->log_reason($tt->error());
371 After the optional third output argument can come an optional
372 reference to a hash or a list of C<(name, value)> pairs providing further
373 options for the output. The only option currently supported is
374 C<binmode> which, when set to any true value will ensure that files
375 created (but not any existing file handles passed) will be set to
378 # either: hash reference of options
379 $tt->process($infile, $vars, $outfile, { binmode => 1 })
380 || die $tt->error(), "\n";
382 # or: list of name, value pairs
383 $tt->process($infile, $vars, $outfile, binmode => 1)
384 || die $tt->error(), "\n";
386 Alternately, the C<binmode> argument can specify a particular IO layer such
389 $tt->process($infile, $vars, $outfile, binmode => ':utf8')
390 || die $tt->error(), "\n";
392 The C<OUTPUT> configuration item can be used to specify a default output
393 location other than C<\*STDOUT>. The C<OUTPUT_PATH> specifies a directory
394 which should be prefixed to all output locations specified as filenames.
396 my $tt = Template->new({
397 OUTPUT => sub { ... }, # default
398 OUTPUT_PATH => '/tmp',
400 }) || die Template->error(), "\n";
402 # use default OUTPUT (sub is called)
403 $tt->process('welcome.tt2', $vars)
404 || die $tt->error(), "\n";
406 # write file to '/tmp/welcome.html'
407 $tt->process('welcome.tt2', $vars, 'welcome.html')
408 || die $tt->error(), "\n";
410 The C<process()> method returns C<1> on success or C<undef> on error. The
411 error message generated in the latter case can be retrieved by calling the
412 L<error()> method. See also L<CONFIGURATION SUMMARY> which describes how error
413 handling may be further customised.
417 When called as a class method, it returns the value of the C<$ERROR> package
418 variable. Thus, the following are equivalent.
420 my $tt = Template->new()
421 || die Template->error(), "\n";
423 my $tt = Template->new()
424 || die $Template::ERROR, "\n";
426 When called as an object method, it returns the value of the internal
427 C<_ERROR> variable, as set by an error condition in a previous call to
430 $tt->process('welcome.tt2')
431 || die $tt->error(), "\n";
433 Errors are represented in the Template Toolkit by objects of the
434 L<Template::Exception> class. If the L<process()> method returns a false value
435 then the C<error()> method can be called to return an object of this class.
436 The L<type()|Template::Exception#type()> and
437 L<info()|Template::Exception#info()> methods can called on the object to
438 retrieve the error type and information string, respectively. The
439 L<as_string()|Template::Exception#as_string()>
440 method can be called to return a string of the form C<$type - $info>. This
441 method is also overloaded onto the stringification operator allowing the
442 object reference itself to be printed to return the formatted error string.
444 $tt->process('somefile') || do {
445 my $error = $tt->error();
446 print "error type: ", $error->type(), "\n";
447 print "error info: ", $error->info(), "\n";
453 The C<Template> module delegates most of the effort of processing templates
454 to an underlying L<Template::Service> object. This method returns a reference
459 The L<Template::Service> module uses a core L<Template::Context> object for
460 runtime processing of templates. This method returns a reference to
461 that object and is equivalent to C<< $template-E<gt>service-E<gt>context() >>.
463 =head1 CONFIGURATION SUMMARY
465 The following list gives a short summary of each Template Toolkit
466 configuration option. See L<Template::Manual::Config> for full details.
468 =head2 Template Style and Parsing Options
470 =head3 START_TAG, END_TAG
472 Define tokens that indicate start and end of directives
473 (default: 'C<[%>' and 'C<%]>').
477 Set C<START_TAG> and C<END_TAG> according to a pre-defined style (default:
478 'C<template>', as above).
480 =head3 PRE_CHOMP, POST_CHOMP
482 Removes whitespace before/after directives (default: 0/0).
486 Remove leading and trailing whitespace from template output (default: 0).
490 Interpolate variables embedded like C<$this> or C<${this}> (default: 0).
494 Allow directive keywords in lower case (default: 0 - UPPER only).
496 =head2 Template Files and Blocks
500 One or more directories to search for templates.
504 Delimiter for separating paths in C<INCLUDE_PATH> (default: 'C<:>').
508 Allow absolute file names, e.g. C</foo/bar.html> (default: 0).
512 Allow relative filenames, e.g. C<../foo/bar.html> (default: 0).
516 Default template to use when another not found.
520 Hash array pre-defining template blocks.
524 Enabled by default causing C<BLOCK> definitions to be reset each time a
525 template is processed. Disable to allow C<BLOCK> definitions to persist.
529 Flag to permit recursion into templates (default: 0).
531 =head2 Template Variables
535 Hash array of variables and values to pre-define in the stash.
537 =head2 Runtime Processing Options
541 Flag to indicate if C<PERL>/C<RAWPERL> blocks should be processed (default: 0).
543 =head3 PRE_PROCESS, POST_PROCESS
545 Name of template(s) to process before/after main template.
549 Name of template(s) to process instead of main template.
553 Name of error template or reference to hash array mapping error types to
558 Default output location or handler.
562 Directory into which output files can be written.
566 Enable debugging messages.
568 =head2 Caching and Compiling Options
572 Maximum number of compiled templates to cache in memory (default:
577 Filename extension for compiled template files (default: undef - don't
582 Root of directory in which compiled template files should be written
583 (default: undef - don't compile).
585 =head2 Plugins and Filters
589 Reference to a hash array mapping plugin names to Perl packages.
593 One or more base classes under which plugins may be found.
597 Flag to indicate regular Perl modules should be loaded if a named plugin
598 can't be found (default: 0).
602 Hash array mapping filter names to filter subroutines or factories.
604 =head2 Customisation and Extension
606 =head3 LOAD_TEMPLATES
608 List of template providers.
612 List of plugin providers.
616 List of filter providers.
620 Set providers to tolerate errors as declinations (default: 0).
624 Reference to a custom service object (default: L<Template::Service>).
628 Reference to a custom context object (default: L<Template::Context>).
632 Reference to a custom stash object (default: L<Template::Stash>).
636 Reference to a custom parser object (default: L<Template::Parser>).
640 Reference to a custom grammar object (default: L<Template::Grammar>).
642 =head1 DIRECTIVE SUMMARY
644 The following list gives a short summary of each Template Toolkit directive.
645 See L<Template::Manual::Directives> for full details.
649 Evaluate and print a variable or value.
651 [% GET variable %] # 'GET' keyword is optional
661 As per L<GET> but without printing result (e.g. call code)
667 Assign a values to variables.
669 [% SET variable = value %] # 'SET' also optional
670 [% variable = other_variable
671 variable = 'literal text @ $100'
672 variable = "interpolated text: $var"
673 list = [ val, val, val, val, ... ]
675 hash = { var => val, var => val, ... }
680 Like L<SET>, but variables are only set if currently unset (i.e. have no
683 [% DEFAULT variable = value %]
687 Insert a file without any processing performed on the contents.
689 [% INSERT legalese.txt %]
693 Process another template file or block and insert the generated output.
694 Any template L<BLOCK>s or variables defined or updated in the C<PROCESS>ed
695 template will thereafter be defined in the calling template.
697 [% PROCESS template %]
698 [% PROCESS template var = val, ... %]
702 Similar to C<PROCESS>, but using a local copy of the current variables.
703 Any template C<BLOCK>s or variables defined in the C<INCLUDE>d template
706 [% INCLUDE template %]
707 [% INCLUDE template var = val, ... %]
711 The content between the C<WRAPPER> and correspondng C<END> directives is first
712 evaluated, with the output generated being stored in the C<content> variable.
713 The named template is then process as per C<INCLUDE>.
716 Some template markup [% blah %]...
719 A simple F<layout> template might look something like this:
727 Define a named template block for L<INCLUDE>, L<PROCESS> and L<WRAPPER>
738 Repeat the enclosed C<FOREACH> ... C<END> block for each value in the list.
740 [% FOREACH variable IN [ val, val, val ] %] # either
741 [% FOREACH variable IN list %] # or
742 The variable is set to [% variable %]
747 The block enclosed between C<WHILE> and C<END> block is processed while
748 the specified condition is true.
750 [% WHILE condition %]
754 =head2 IF / UNLESS / ELSIF / ELSE
756 The enclosed block is processed if the condition is true / false.
760 [% ELSIF condition %]
766 [% UNLESS condition %]
768 [% # ELSIF/ELSE as per IF, above %]
774 Multi-way switch/case statement.
776 [% SWITCH variable %]
779 [% CASE [ val2, val3 ] %]
781 [% CASE %] # or [% CASE DEFAULT %]
787 Define a named macro.
789 [% MACRO name <directive> %]
790 [% MACRO name(arg1, arg2) <directive> %]
793 [% name(val1, val2) %]
797 Process enclosed C<FILTER> ... C<END> block then pipe through a filter.
799 [% FILTER name %] # either
800 [% FILTER name( params ) %] # or
801 [% FILTER alias = name( params ) %] # or
807 Load a plugin module (see C<Template::<Manual::Plugins>), or any regular Perl
808 module when the C<LOAD_PERL> option is set.
810 [% USE name %] # either
811 [% USE name( params ) %] # or
812 [% USE var = name( params ) %] # or
817 =head2 PERL / RAWPERL
819 Evaluate enclosed blocks as Perl code (requires the C<EVAL_PERL> option to be
823 # perl code goes here
824 $stash->set('foo', 10);
825 print "set 'foo' to ", $stash->get('foo'), "\n";
826 print $context->include('footer', { var => $val });
830 # raw perl code goes here, no magic but fast.
831 $output .= 'some output';
834 =head2 TRY / THROW / CATCH / FINAL
840 [% THROW type info %]
843 [% error.type %] [% error.info %]
844 [% CATCH %] # or [% CATCH DEFAULT %]
847 this block is always processed
852 Jump straight to the next item in a C<FOREACH> or C<WHILE> loop.
858 Break out of C<FOREACH> or C<WHILE> loop.
864 Stop processing current template and return to including templates.
870 Stop processing all templates and return to caller.
876 Define new tag style or characters (default: C<[%> C<%]>).
885 [% # this is a comment to the end of line
889 [%# placing the '#' immediately inside the directive
890 tag comments out the entire directive
895 Andy Wardley E<lt>abw@wardley.orgE<gt> L<http://wardley.org/>
899 Template Toolkit version 2.20_1, released April 2009.
903 Copyright (C) 1996-2009 Andy Wardley. All Rights Reserved.
905 This module is free software; you can redistribute it and/or
906 modify it under the same terms as Perl itself.
912 # perl-indent-level: 4
913 # indent-tabs-mode: nil
916 # vim: expandtab shiftwidth=4: