use Template::Context; # constructor $context = Template::Context->new(\%config) || die $Template::Context::ERROR; # fetch (load and compile) a template $template = $context->template($template_name); # fetch (load and instantiate) a plugin object $plugin = $context->plugin($name, \@args); # fetch (return or create) a filter subroutine $filter = $context->filter($name, \@args, $alias); # process/include a template, errors are thrown via die() $output = $context->process($template, \%vars); $output = $context->include($template, \%vars); # raise an exception via die() $context->throw($error_type, $error_message, \$output_buffer); # catch an exception, clean it up and fix output buffer $exception = $context->catch($exception, \$output_buffer); # save/restore the stash to effect variable localisation $new_stash = $context->localise(\%vars); $old_stash = $context->delocalise(); # add new BLOCK or FILTER definitions $context->define_block($name, $block); $context->define_filter($name, \&filtersub, $is_dynamic); # reset context, clearing any imported BLOCK definitions $context->reset(); # methods for accessing internal items $stash = $context->stash(); $tflag = $context->trim(); $epflag = $context->eval_perl(); $providers = $context->templates(); $providers = $context->plugins(); $providers = $context->filters(); ...
A default "Template::Context" object is created by the Template module. Any "Template::Context" options may be passed to the Template new() constructor method and will be forwarded to the "Template::Context" constructor.
use Template; my $template = Template->new({ TRIM => 1, EVAL_PERL => 1, BLOCKS => { header => 'This is the header', footer => 'This is the footer', }, });
Similarly, the "Template::Context" constructor will forward all configuration parameters onto other default objects (e.g. Template::Provider, Template::Plugins, Template::Filters, etc.) that it may need to instantiate.
$context = Template::Context->new({ INCLUDE_PATH => '/home/abw/templates', # provider option TAG_STYLE => 'html', # parser option });
A "Template::Context" object (or subclass) can be explicitly instantiated and passed to the Template new() constructor method as the "CONTEXT" configuration item.
use Template; use Template::Context; my $context = Template::Context->new({ TRIM => 1 }); my $template = Template->new({ CONTEXT => $context });
The Template module uses the Template::Config context() factory method to create a default context object when required. The $Template::Config::CONTEXT package variable may be set to specify an alternate context module. This will be loaded automatically and its new() constructor method called by the context() factory method when a default context object is required.
use Template; $Template::Config::CONTEXT = 'MyOrg::Template::Context'; my $template = Template->new({ EVAL_PERL => 1, EXTRA_MAGIC => 'red hot', # your extra config items ... });
my $context = Template::Context->new({ INCLUDE_PATH => 'header', POST_PROCESS => 'footer', }); my $context = Template::Context->new( EVAL_PERL => 1 );
The "new()" method returns a "Template::Context" object or "undef" on error. In the latter case, a relevant error message can be retrieved by the error() class method or directly from the $Template::Context::ERROR package variable.
my $context = Template::Context->new(\%config) || die Template::Context->error(); my $context = Template::Context->new(\%config) || die $Template::Context::ERROR;
The following configuration items may be specified. Please see Template::Manual::Config for further details.
VARIABLES
The VARIABLES option can be used to specify a hash array of template variables.
my $context = Template::Context->new({ VARIABLES => { title => 'A Demo Page', author => 'Joe Random Hacker', version => 3.14, }, };
BLOCKS
The BLOCKS option can be used to pre-define a default set of template blocks.
my $context = Template::Context->new({ BLOCKS => { header => 'The Header. [% title %]', footer => sub { return $some_output_text }, another => Template::Document->new({ ... }), }, });
VIEWS
The VIEWS option can be used to pre-define one or more Template::View objects.
my $context = Template::Context->new({ VIEWS => [ bottom => { prefix => 'bottom/' }, middle => { prefix => 'middle/', base => 'bottom' }, top => { prefix => 'top/', base => 'middle' }, ], });
TRIM
The TRIM option can be set to have any leading and trailing whitespace automatically removed from the output of all template files and "BLOCK"s.
example:
[% BLOCK foo %] Line 1 of foo [% END %] before [% INCLUDE foo %] after
output:
before Line 1 of foo after
EVAL_PERL
The EVAL_PERL is used to indicate if "PERL" and/or "RAWPERL" blocks should be evaluated. It is disabled by default.
RECURSION
The RECURSION can be set to allow templates to recursively process themselves, either directly (e.g. template "foo" calls "INCLUDE foo") or indirectly (e.g. "foo" calls "INCLUDE bar" which calls "INCLUDE foo").
LOAD_TEMPLATES
The LOAD_TEMPLATES option can be used to provide a reference to a list of Template::Provider objects or sub-classes thereof which will take responsibility for loading and compiling templates.
my $context = Template::Context->new({ LOAD_TEMPLATES => [ MyOrg::Template::Provider->new({ ... }), Template::Provider->new({ ... }), ], });
LOAD_PLUGINS
The LOAD_PLUGINS options can be used to specify a list of provider objects responsible for loading and instantiating template plugin objects.
my $context = Template::Context->new({ LOAD_PLUGINS => [ MyOrg::Template::Plugins->new({ ... }), Template::Plugins->new({ ... }), ], });
LOAD_FILTERS
The LOAD_FILTERS option can be used to specify a list of provider objects for returning and/or creating filter subroutines.
my $context = Template::Context->new({ LOAD_FILTERS => [ MyTemplate::Filters->new(), Template::Filters->new(), ], });
STASH
The STASH option can be used to specify a Template::Stash object or sub-class which will take responsibility for managing template variables.
my $stash = MyOrg::Template::Stash->new({ ... }); my $context = Template::Context->new({ STASH => $stash, });
DEBUG
The DEBUG option can be used to enable various debugging features of the Template::Context module.
use Template::Constants qw( :debug ); my $template = Template->new({ DEBUG => DEBUG_CONTEXT | DEBUG_DIRS, });
$template = $context->template('header');
On error, a Template::Exception object of type '"file"' is thrown via "die()". This can be caught by enclosing the call to "template()" in an "eval" block and examining $@.
eval { $template = $context->template('header') }; if ($@) { print "failed to fetch template: $@\n"; }
Returns a reference to a plugin (which is generally an object, but doesn't have to be). Errors are thrown as Template::Exception objects with the type set to '"plugin"'.
$plugin = $context->plugin('DBI', 'dbi:msql:mydbname');
Additional arguments may be passed by list reference along with an optional alias under which the filter will be cached for subsequent use. The filter is cached under its own $name if $alias is undefined. Subsequent calls to "filter($name)" will return the cached entry, if defined. Specifying arguments bypasses the caching mechanism and always creates a new filter. Errors are thrown as Template::Exception objects with the type set to '"filter"'.
# static filter (no args) $filter = $context->filter('html'); # dynamic filter (args) aliased to 'padright' $filter = $context->filter('format', '%60s', 'padright'); # retrieve previous filter via 'padright' alias $filter = $context->filter('padright');
$output = $context->process('header', { title => 'Hello World' });
$output = $context->include('header', { title => 'Hello World' });
$context->throw($exception); $context->throw("I'm sorry Dave, I can't do that"); $context->throw('denied', "I'm sorry Dave, I can't do that");
The optional third parameter may be a reference to the current output buffer. This is then stored in the exception object when created, allowing the catcher to examine and use the output up to the point at which the exception was raised.
$output .= 'blah blah blah'; $output .= 'more rhubarb'; $context->throw('yack', 'Too much yacking', \$output);
Returns a true value (the sub-routine or Template::Document reference) on success or undef on failure. The relevant error message can be retrieved by calling the error() method.
Returns a true value or throws a '"filter"' exception on error.
# define a new scalar (item) virtual method $context->define_vmethod( item => ucfirst => sub { my $text = shift; return ucfirst $text; } )
$context->define_view( my_view => { prefix => 'my_templates/' } );
The view is then accessible as a template variable.
[% my_view.print(some_data) %]
$context->define_view({ # hash reference my_view_one => { prefix => 'my_templates_one/' }, my_view_two => { prefix => 'my_templates_two/' } });
If you're defining multiple views of which one or more are based on other views in the same definition then you should pass them as a list reference. This ensures that they get created in the right order (Perl does not preserve the order of items defined in a hash reference so you can't guarantee that your base class view will be defined before your subclass view).
$context->define_view([ # list referenence my_view_one => { prefix => 'my_templates_one/' }, my_view_two => { prefix => 'my_templates_two/' , base => 'my_view_one', } ]);
The views are then accessible as template variables.
[% my_view_one.print(some_data) %] [% my_view_two.print(some_data) %]
$stash = $context->localise();
$stash = $context->delocalise();
The first argument can be "on" or "off" to enable or disable debugging respectively. The numerical values 0 and 1 can also be used if you prefer.
$context->debugging('on');
Alternately, the first argument can be "format" to define a new debug message format. The second argument should be the format string which can contain any of the $file, $line or $text symbols to indicate where the relevant values should be inserted.
# note single quotes to prevent interpolated of variables $context->debugging( format => '## $file line $line: $text' );
The final use of this method is to generate debugging messages themselves. The first argument should be "msg", followed by a reference to a hash array of value to insert into the debugging format string.
$context->debugging( msg => { line => 20, file => 'example.tt', text => 'Trampoline! Trampoline!', } );
$stash = $context->stash(); $tflag = $context->trim(); $epflag = $context->eval_perl(); ...
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.