Template::Context - Runtime context in which templates are processed
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/derivative) can be explicitly instantiated and passed to the Template new() constructor method as the CONTEXT 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 sub-class) 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.
my $context = Template::Context->new({ VARIABLES => { title => 'A Demo Page', author => 'Joe Random Hacker', version => 3.14, }, };
or
my $context = Template::Context->new({ PRE_DEFINE => { title => 'A Demo Page', author => 'Joe Random Hacker', version => 3.14, }, };
my $context = Template::Context->new({ BLOCKS => { header => 'The Header. [% title %]', footer => sub { return $some_output_text }, another => Template::Document->new({ ... }), }, });
By example, the following BLOCK definition
[% BLOCK foo %] Line 1 of foo [% END %]
will be processed is as ``\nLine 1 of foo\n''. When INCLUDEd, the surrounding newlines will also be introduced.
before [% INCLUDE foo %] after
output:
before
Line 1 of foo
after
With the TRIM option set to any true value, the leading and trailing newlines (which count as whitespace) will be removed from the output of the BLOCK.
before Line 1 of foo after
The TRIM option is disabled (0) by default.
When using compiled templates (see COMPILE_EXT and COMPILE_DIR), the EVAL_PERL has an affect when the template is compiled, and again when the templates is subsequently processed, possibly in a different context to the one that compiled it.
If the EVAL_PERL is set when a template is compiled, then all PERL and RAWPERL blocks will be included in the compiled template. If the EVAL_PERL option isn't set, then Perl code will be generated which always throws a 'perl' exception with the message 'EVAL_PERL not set' whenever the compiled template code is run.
Thus, you must have EVAL_PERL set if you want your compiled templates to include PERL and RAWPERL blocks.
At some point in the future, using a different invocation of the Template Toolkit, you may come to process such a pre-compiled template. Assuming the EVAL_PERL option was set at the time the template was compiled, then the output of any RAWPERL blocks will be included in the compiled template and will get executed when the template is processed. This will happen regardless of the runtime EVAL_PERL status.
Regular PERL blocks are a little more cautious, however. If the EVAL_PERL flag isn't set for the current context, that is, the one which is trying to process it, then it will throw the familiar 'perl' exception with the message, 'EVAL_PERL not set'.
Thus you can compile templates to include PERL blocks, but optionally disable them when you process them later. Note however that it is possible for a PERL block to contain a Perl ``BEGIN { # some code }'' block which will always get run regardless of the runtime EVAL_PERL status. Thus, if you set EVAL_PERL when compiling templates, it is assumed that you trust the templates to Do The Right Thing. Otherwise you must accept the fact that there's no bulletproof way to prevent any included code from trampling around in the living room of the runtime environment, making a real nuisance of itself if it really wants to. If you don't like the idea of such uninvited guests causing a bother, then you can accept the default and keep EVAL_PERL disabled.
my $context = Template::Context->new({ LOAD_TEMPLATES => [ MyOrg::Template::Provider->new({ ... }), Template::Provider->new({ ... }), ], });
When a PROCESS, INCLUDE or WRAPPER directive is encountered, the named template may refer to a locally defined BLOCK or a file relative to the INCLUDE_PATH (or an absolute or relative path if the appropriate ABSOLUTE or RELATIVE options are set). If a BLOCK definition can't be found (see the Template::Context template() method for a discussion of BLOCK locality) then each of the LOAD_TEMPLATES provider objects is queried in turn via the fetch() method to see if it can supply the required template. Each provider can return a compiled template, an error, or decline to service the request in which case the responsibility is passed to the next provider. If none of the providers can service the request then a 'not found' error is returned. The same basic provider mechanism is also used for the INSERT directive but it bypasses any BLOCK definitions and doesn't attempt is to parse or process the contents of the template file.
This is an implementation of the 'Chain of Responsibility' design pattern as described in ``Design Patterns'', Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides), Addision-Wesley, ISBN 0-201-63361-2, page 223 .
If LOAD_TEMPLATES is undefined, a single default provider will be instantiated using the current configuration parameters. For example, the Template::Provider INCLUDE_PATH option can be specified in the Template::Context configuration and will be correctly passed to the provider's constructor method.
my $context = Template::Context->new({ INCLUDE_PATH => '/here:/there', });
my $context = Template::Context->new({ LOAD_PLUGINS => [ MyOrg::Template::Plugins->new({ ... }), Template::Plugins->new({ ... }), ], });
By default, a single Template::Plugins object is created using the current configuration hash. Configuration items destined for the Template::Plugins constructor may be added to the Template::Context constructor.
my $context = Template::Context->new({ PLUGIN_BASE => 'MyOrg::Template::Plugins', LOAD_PERL => 1, });
my $context = Template::Context->new({ LOAD_FILTERS => [ MyTemplate::Filters->new(), Template::Filters->new(), ], });
By default, a single Template::Filters object is created for the LOAD_FILTERS list.
my $stash = MyOrg::Template::Stash->new({ ... }); my $context = Template::Context->new({ STASH => $stash, });
If unspecified, a default stash object is created using the VARIABLES configuration item to initialise the stash variables. These may also be specified as the PRE_DEFINE option for backwards compatibility with version 1.
my $context = Template::Context->new({ VARIABLES => { id => 'abw', name => 'Andy Wardley', }, };
use Template::Constants qw( :debug );
my $template = Template->new({ DEBUG => DEBUG_CONTEXT | DEBUG_DIRS, });
The DEBUG value can include any of the following. Multiple values should be combined using the logical OR operator, '|'.
For example, the following template fragment:
Hello World
would generate this output:
## input text line 1 : ## Hello ## input text line 2 : World ## World
$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 of type 'plugin'.
$plugin = $context->plugin('DBI', 'dbi:msql:mydbname');
# 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);
$stash = $context->localise();
$stash = $context->delocalise();
$stash = $context->stash(); $tflag = $context->trim(); $epflag = $context->eval_perl(); ...
<http://www.andywardley.com/|http://www.andywardley.com/>
Copyright (C) 1996-2004 Andy Wardley. All Rights Reserved. Copyright (C) 1998-2002 Canon Research Centre Europe Ltd.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Закладки на сайте Проследить за страницей |
Created 1996-2024 by Maxim Chirkov Добавить, Поддержать, Вебмастеру |