#============================================================= -*-perl-*- # # Template::Manual::Config # # AUTHOR # Andy Wardley # # COPYRIGHT # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # #======================================================================== =head1 NAME Template::Manual::Config - Configuration options =head1 Template Style and Parsing Options =head2 ENCODING The C option specifies the template files' character encoding: my $template = Template->new({ ENCODING => 'utf8', }); A template which starts with a Unicode byte order mark (BOM) will have its encoding detected automatically. =head2 START_TAG, END_TAG The C and C options are used to specify character sequences or regular expressions that mark the start and end of inline template directives. The default values for C and C are 'C<[%>' and 'C<%]>' respectively, giving us the familiar directive style: [% example %] Any Perl regex characters can be used and therefore should be escaped (or use the Perl C function) if they are intended to represent literal characters. my $template = Template->new({ START_TAG => quotemeta('<+'), END_TAG => quotemeta('+>'), }); Example: <+ INCLUDE foobar +> The C directive can also be used to set the C and C values on a per-template file basis. [% TAGS <+ +> %] =head2 OUTLINE_TAG The C option can be used to enable single-line "outline" directives. my $template = Template->new({ OUTLINE_TAG => '%%', }); This allows you to use both inline and outline tags like so: %% IF user Hello [% user.name %] %% END The C string (or regex) must appear at the start of a line. The directive continues until the end of the line. The newline character at the end of the line is considered to be the invisible end-of-directive marker and is removed. =head2 TAG_STYLE The C option can be used to set both C and C according to pre-defined tag styles. my $template = Template->new({ TAG_STYLE => 'star', }); Available styles are: template [% ... %] (default) template1 [% ... %] or %% ... %% (TT version 1) metatext %% ... %% (Text::MetaText) star [* ... *] (TT alternate) php (PHP) asp <% ... %> (ASP) mason <% ... > (HTML::Mason) html (HTML comments) The C style uses the default markers for C and C (C<[%> and C<%]> respectively) and additionally defines C to be C<%%>. my $template = Template->new({ TAG_STYLE => 'outline', }); This allows you to use both inline and outline tags like so: %% IF user Hello [% user.name %] %% END Any values specified for C, C and/or C will override those defined by a C. The C directive may also be used to set a C [% TAGS html %] =head2 PRE_CHOMP, POST_CHOMP Anything outside a directive tag is considered plain text and is generally passed through unaltered (but see the L option). This includes all whitespace and newlines characters surrounding directive tags. Directives that don't generate any output will leave gaps in the output document. Example: Foo [% a = 10 %] Bar Output: Foo Bar The C and C options can help to clean up some of this extraneous whitespace. Both are disabled by default. my $template = Template->new({ PRE_CHOMP => 1, POST_CHOMP => 1, }); With C set to C<1>, the newline and whitespace preceding a directive at the start of a line will be deleted. This has the effect of concatenating a line that starts with a directive onto the end of the previous line. Foo <----------. | ,---(PRE_CHOMP)----' | `-- [% a = 10 %] --. | ,---(POST_CHOMP)---' | `-> Bar With C set to C<1>, any whitespace after a directive up to and including the newline will be deleted. This has the effect of joining a line that ends with a directive onto the start of the next line. If C or C is set to C<2>, all whitespace including any number of newline will be removed and replaced with a single space. This is useful for HTML, where (usually) a contiguous block of whitespace is rendered the same as a single space. With C or C set to C<3>, all adjacent whitespace (including newlines) will be removed entirely. These values are defined as C, C, C and C constants in the L module. C is also defined as an alias for C to provide backwards compatibility with earlier version of the Template Toolkit. Additionally the chomp tag modifiers listed below may also be used for the C and C configuration. my $template = Template->new({ PRE_CHOMP => '~', POST_CHOMP => '-', }); C and C can be activated for individual directives by placing a 'C<->' immediately at the start and/or end of the directive. [% FOREACH user IN userlist %] [%- user -%] [% END %] This has the same effect as C in removing all whitespace before or after the directive up to and including the newline. The template will be processed as if written: [% FOREACH user IN userlist %][% user %][% END %] To remove all whitespace including any number of newlines, use the ('C<~>') tilde character instead. [% FOREACH user IN userlist %] [%~ user ~%] [% END %] To collapse all whitespace to a single space, use the 'C<=>' equals sign character. [% FOREACH user IN userlist %] [%= user =%] [% END %] Here the template is processed as if written: [% FOREACH user IN userlist %] [% user %] [% END %] If you have C or C set as configuration options then you can use the 'C<+>' plus sign to disable any chomping options (i.e. leave the whitespace intact) on a per-directive basis. [% FOREACH user IN userlist %] User: [% user +%] [% END %] With C set to C, the above example would be parsed as if written: [% FOREACH user IN userlist %]User: [% user %] [% END %] For reference, the C and C configuration options may be set to any of the following: Constant Value Tag Modifier ---------------------------------- CHOMP_NONE 0 + CHOMP_ONE 1 - CHOMP_COLLAPSE 2 = CHOMP_GREEDY 3 ~ =head2 TRIM The C option can be set to have any leading and trailing whitespace automatically removed from the output of all template files and Cs. By example, the following C definition [% BLOCK foo %] Line 1 of foo [% END %] will be processed is as "C<\nLine 1 of foo\n>". When Cd, the surrounding newlines will also be introduced. before [% INCLUDE foo %] after Generated output: before Line 1 of foo after With the C option set to any true value, the leading and trailing newlines (which count as whitespace) will be removed from the output of the C. before Line 1 of foo after The C option is disabled (C<0>) by default. =head2 INTERPOLATE The C flag, when set to any true value will cause variable references in plain text (i.e. not surrounded by C and C) to be recognised and interpolated accordingly. my $template = Template->new({ INTERPOLATE => 1, }); Variables should be prefixed by a 'C<$>' dollar sign to identify them. Curly braces 'C<{>' and 'C<}>' can be used in the familiar Perl/shell style to explicitly scope the variable name where required. # INTERPOLATE => 0 [% myorg.name %] # INTERPOLATE => 1 $myorg.name # explicit scoping with { } Note that a limitation in Perl's regex engine restricts the maximum length of an interpolated template to around 32 kilobytes or possibly less. Files that exceed this limit in size will typically cause Perl to dump core with a segmentation fault. If you routinely process templates of this size then you should disable C or split the templates in several smaller files or blocks which can then be joined backed together via C or C. =head2 ANYCASE By default, directive keywords should be expressed in UPPER CASE. The C option can be set to allow directive keywords to be specified in any case. # ANYCASE => 0 (default) [% INCLUDE foobar %] # OK [% include foobar %] # ERROR [% include = 10 %] # OK, 'include' is a variable # ANYCASE => 1 [% INCLUDE foobar %] # OK [% include foobar %] # OK [% include = 10 %] # ERROR, 'include' is reserved word One side-effect of enabling C is that you cannot use a variable of the same name as a reserved word, regardless of case. The reserved words are currently: GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP CLEAR TO STEP AND OR NOT MOD DIV END The only lower case reserved words that cannot be used for variables, regardless of the C option, are the operators: and or not mod div =head1 Template Files and Blocks =head2 INCLUDE_PATH The C is used to specify one or more directories in which template files are located. When a template is requested that isn't defined locally as a C, each of the C directories is searched in turn to locate the template file. Multiple directories can be specified as a reference to a list or as a single string where each directory is delimited by the 'C<:>' colon character. my $template = Template->new({ INCLUDE_PATH => '/usr/local/templates', }); my $template = Template->new({ INCLUDE_PATH => '/usr/local/templates:/tmp/my/templates', }); my $template = Template->new({ INCLUDE_PATH => [ '/usr/local/templates', '/tmp/my/templates' ], }); On Win32 systems, a little extra magic is invoked, ignoring delimiters that have 'C<:>' colon followed by a 'C' slash or 'C<\>' blackslash. This avoids confusion when using directory names like 'C'. When specified as a list, the C path can contain elements which dynamically generate a list of C directories. These generator elements can be specified as a reference to a subroutine or an object which implements a C method. my $template = Template->new({ INCLUDE_PATH => [ '/usr/local/templates', \&incpath_generator, My::IncPath::Generator->new( ... ) ], }); Each time a template is requested and the C examined, the subroutine or object method will be called. A reference to a list of directories should be returned. Generator subroutines should report errors using C. Generator objects should return undef and make an error available via its C method. For example: sub incpath_generator { # ...some code... if ($all_is_well) { return \@list_of_directories; } else { die "cannot generate INCLUDE_PATH...\n"; } } or: package My::IncPath::Generator; # Template::Base (or Class::Base) provides error() method use Template::Base; use base qw( Template::Base ); sub paths { my $self = shift; # ...some code... if ($all_is_well) { return \@list_of_directories; } else { return $self->error("cannot generate INCLUDE_PATH...\n"); } } 1; =head2 DELIMITER Used to provide an alternative delimiter character sequence for separating paths specified in the C. The default value for C is the 'C<:>' colon character. my $template = Template->new({ DELIMITER => '; ', INCLUDE_PATH => 'C:/HERE/NOW; D:/THERE/THEN', }); On Win32 systems, the default delimiter is a little more intelligent, splitting paths only on 'C<:>' colon characters that aren't followed by a 'C' slash character. This means that the following should work as planned, splitting the C into 2 separate directories, C and C. # on Win32 only my $template = Template->new({ INCLUDE_PATH => 'C:/Foo:C:/Bar' }); However, if you're using Win32 then it's recommended that you explicitly set the C character to something else (e.g. 'C<;>' semicolon) rather than rely on this subtle magic. =head2 ABSOLUTE The C flag is used to indicate if templates specified with absolute filenames (e.g. 'C') should be processed. It is disabled by default and any attempt to load a template by such a name will cause a 'C' exception to be raised. my $template = Template->new({ ABSOLUTE => 1, }); # this is why it's disabled by default [% INSERT /etc/passwd %] On Win32 systems, the regular expression for matching absolute pathnames is tweaked slightly to also detect filenames that start with a driver letter and colon, such as: C:/Foo/Bar =head2 RELATIVE The C flag is used to indicate if templates specified with filenames relative to the current directory (e.g. 'C<./foo/bar>' or 'C<../../some/where/else>') should be loaded. It is also disabled by default, and will raise a 'C' error if such template names are encountered. my $template = Template->new({ RELATIVE => 1, }); [% INCLUDE ../logs/error.log %] =head2 DEFAULT The C option can be used to specify a default template which should be used whenever a specified template can't be found in the C. my $template = Template->new({ DEFAULT => 'notfound.html', }); If a non-existent template is requested through the Template L method, or by an C, C or C directive, then the C template will instead be processed, if defined. Note that the C template is not used when templates are specified with absolute or relative filenames, or as a reference to a input file handle or text string. =head2 BLOCKS The C option can be used to pre-define a default set of template blocks. These should be specified as a reference to a hash array mapping template names to template text, subroutines or L objects. my $template = Template->new({ BLOCKS => { header => 'The Header. [% title %]', footer => sub { return $some_output_text }, another => Template::Document->new({ ... }), }, }); =head2 VIEWS The VIEWS option can be used to define one or more L objects. They can be specified as a reference to a hash array or list reference. my $template = Template->new({ VIEWS => { my_view => { prefix => 'my_templates/' }, }, }); Be aware of the fact that Perl's hash array are unordered, so if you want to specify multiple views of which one or more are based on other views, then you should use a list reference to preserve the order of definition. my $template = Template->new({ VIEWS => [ bottom => { prefix => 'bottom/' }, middle => { prefix => 'middle/', base => 'bottom' }, top => { prefix => 'top/', base => 'middle' }, ], }); =head2 AUTO_RESET The C option is set by default and causes the local C cache for the L object to be reset on each call to the Template L method. This ensures that any Cs defined within a template will only persist until that template is finished processing. This prevents Cs defined in one processing request from interfering with other independent requests subsequently processed by the same context object. The C item may be used to specify a default set of block definitions for the L object. Subsequent C definitions in templates will over-ride these but they will be reinstated on each reset if C is enabled (default), or if the L L method is called. =head2 RECURSION The template processor will raise a file exception if it detects direct or indirect recursion into a template. Setting this option to any true value will allow templates to include each other recursively. =head1 Template Variables =head2 VARIABLES The C option (or C - they're equivalent) can be used to specify a hash array of template variables that should be used to pre-initialise the stash when it is created. These items are ignored if the C item is defined. my $template = Template->new({ VARIABLES => { title => 'A Demo Page', author => 'Joe Random Hacker', version => 3.14, }, }; or my $template = Template->new({ PRE_DEFINE => { title => 'A Demo Page', author => 'Joe Random Hacker', version => 3.14, }, }; =head2 CONSTANTS The C option can be used to specify a hash array of template variables that are compile-time constants. These variables are resolved once when the template is compiled, and thus don't require further resolution at runtime. This results in significantly faster processing of the compiled templates and can be used for variables that don't change from one request to the next. my $template = Template->new({ CONSTANTS => { title => 'A Demo Page', author => 'Joe Random Hacker', version => 3.14, }, }; =head2 CONSTANT_NAMESPACE Constant variables are accessed via the C namespace by default. [% constants.title %] The C option can be set to specify an alternate namespace. my $template = Template->new({ CONSTANTS => { title => 'A Demo Page', # ...etc... }, CONSTANTS_NAMESPACE => 'const', }; In this case the constants would then be accessed as: [% const.title %] =head2 NAMESPACE The constant folding mechanism described above is an example of a namespace handler. Namespace handlers can be defined to provide alternate parsing mechanisms for variables in different namespaces. Under the hood, the L