[%# # IMPORTANT NOTE # This documentation is generated automatically from source # templates. Any changes you make here may be lost. # # The 'docsrc' documentation source bundle is available for download # from http://www.template-toolkit.org/docs.html and contains all # the source templates, XML files, scripts, etc., from which the # documentation for the Template Toolkit is built. -%] [% META book = 'Modules' page = 'Context' %] [% WRAPPER toc; PROCESS tocitem title ="SYNOPSIS" subs = []; PROCESS tocitem title ="DESCRIPTION" subs = []; PROCESS tocitem title ="METHODS" subs = [ "new(\\%params) ", "template(\$name) ", "plugin(\$name, \\@args)", "filter(\$name, \\@args, \$alias)", "process(\$template, \\%vars)", "include(\$template, \\%vars)", "throw(\$error_type, \$error_message, \\\$output)", "catch(\$exception, \\\$output)", "define_block(\$name, \$block)", "define_filter(\$name, \\&filter, \$is_dynamic)", "localise(\\%vars)", "delocalise()", "visit(\\%blocks)", "leave()", "reset()", "AUTOLOAD" ]; PROCESS tocitem title ="AUTHOR" subs = []; PROCESS tocitem title ="VERSION" subs = []; PROCESS tocitem title ="COPYRIGHT" subs = []; PROCESS tocitem title ="SEE ALSO" subs = []; END %] [% WRAPPER section title="SYNOPSIS" -%]
    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();
    ...
[%- END %] [% WRAPPER section title="DESCRIPTION" -%]

The Template::Context module defines an object class for representing a runtime context in which templates are processed. It provides an interface to the fundamental operations of the Template Toolkit processing engine through which compiled templates (i.e. Perl code constructed from the template source) can process templates, load plugins and filters, raise exceptions and so on.

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
	...
    });
[%- END %] [% WRAPPER section title="METHODS" -%][% WRAPPER subsection title = "new(\\%params) " -%]

The new() constructor method is called to instantiate a Template::Context object. Configuration parameters may be specified as a HASH reference or as a list of (name => value) pairs.

    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.

[%- END %] [% WRAPPER subsection title = "template(\$name) " -%]

Returns a compiled template by querying each of the LOAD_TEMPLATES providers (instances of Template::Provider, or sub-class) in turn.

    $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";
    }
[%- END %] [% WRAPPER subsection title = "plugin(\$name, \\@args)" -%]

Instantiates a plugin object by querying each of the LOAD_PLUGINS providers. The default LOAD_PLUGINS provider is a Template::Plugins object which attempts to load plugin modules, according the various configuration items such as PLUGIN_BASE, LOAD_PERL, etc., and then instantiate an object via new(). A reference to a list of constructor arguments may be passed as the second parameter. These are forwarded to the plugin constructor.

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');
[%- END %] [% WRAPPER subsection title = "filter(\$name, \\@args, \$alias)" -%]

Instantiates a filter subroutine by querying the LOAD_FILTERS providers. The default LOAD_FILTERS providers is a Template::Filters object. 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 of typre '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');
[%- END %] [% WRAPPER subsection title = "process(\$template, \\%vars)" -%]

Processes a template named or referenced by the first parameter and returns the output generated. An optional reference to a hash array may be passed as the second parameter, containing variable definitions which will be set before the template is processed. The template is processed in the current context, with no localisation of variables performed. Errors are thrown as Template::Exception objects via die().

    $output = $context->process('header', { title => 'Hello World' });
[%- END %] [% WRAPPER subsection title = "include(\$template, \\%vars)" -%]

Similar to process() above, but using localised variables. Changes made to any variables will only persist until the include() method completes.

    $output = $context->include('header', { title => 'Hello World' });
[%- END %] [% WRAPPER subsection title = "throw(\$error_type, \$error_message, \\\$output)" -%]

Raises an exception in the form of a Template::Exception object by calling die(). This method may be passed a reference to an existing Template::Exception object; a single value containing an error message which is used to instantiate a Template::Exception of type 'undef'; or a pair of values representing the exception type and info from which a Template::Exception object is instantiated. e.g.

    $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);
[%- END %] [% WRAPPER subsection title = "catch(\$exception, \\\$output)" -%]

Catches an exception thrown, either as a reference to a Template::Exception object or some other value. In the latter case, the error string is promoted to a Template::Exception object of 'undef' type. This method also accepts a reference to the current output buffer which is passed to the Template::Exception constructor, or is appended to the output buffer stored in an existing Template::Exception object, if unique (i.e. not the same reference). By this process, the correct state of the output buffer can be reconstructed for simple or nested throws.

[%- END %] [% WRAPPER subsection title = "define_block(\$name, \$block)" -%]

Adds a new block definition to the internal BLOCKS cache. The first argument should contain the name of the block and the second a reference to a Template::Document object or template sub-routine, or template text which is automatically compiled into a template sub-routine. 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.

[%- END %] [% WRAPPER subsection title = "define_filter(\$name, \\&filter, \$is_dynamic)" -%]

Adds a new filter definition by calling the store() method on each of the LOAD_FILTERS providers until accepted (in the usual case, this is accepted straight away by the one and only Template::Filters provider). The first argument should contain the name of the filter and the second a reference to a filter subroutine. The optional third argument can be set to any true value to indicate that the subroutine is a dynamic filter factory. Returns a true value or throws a 'filter' exception on error.

[%- END %] [% WRAPPER subsection title = "localise(\\%vars)" -%]

Clones the stash to create a context with localised variables. Returns a reference to the newly cloned stash object which is also stored internally.

    $stash = $context->localise();
[%- END %] [% WRAPPER subsection title = "delocalise()" -%]

Restore the stash to its state prior to localisation.

    $stash = $context->delocalise();
[%- END %] [% WRAPPER subsection title = "visit(\\%blocks)" -%]

This method is called by Template::Document objects immediately before they process their content. It is called to register any local BLOCK definitions with the context object so that they may be subsequently delivered on request.

[%- END %] [% WRAPPER subsection title = "leave()" -%]

Compliment to visit(), above. Called by Template::Document objects immediately after they process their content.

[%- END %] [% WRAPPER subsection title = "reset()" -%]

Clears the local BLOCKS cache of any BLOCK definitions. Any initial set of BLOCKS specified as a configuration item to the constructor will be reinstated.

[%- END %] [% WRAPPER subsection title = "AUTOLOAD" -%]

An AUTOLOAD method provides access to context configuration items.

    $stash     = $context->stash();
    $tflag     = $context->trim();
    $epflag    = $context->eval_perl();
    ...
[%- END %] [%- END %] [% WRAPPER section title="AUTHOR" -%]

Andy Wardley <abw@wardley.org>

[% ttlink('http://wardley.org/', 'http://wardley.org/') -%]

[%- END %] [% WRAPPER section title="VERSION" -%]

2.98, distributed as part of the Template Toolkit version 2.19, released on 27 April 2007.

[%- END %] [% WRAPPER section title="COPYRIGHT" -%]
  Copyright (C) 1996-2007 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.

[%- END %] [% WRAPPER section title="SEE ALSO" -%]

[% ttlink('Template', 'Template') -%], [% ttlink('Template::Document', 'Template::Document') -%], [% ttlink('Template::Exception', 'Template::Exception') -%], [% ttlink('Template::Filters', 'Template::Filters') -%], [% ttlink('Template::Plugins', 'Template::Plugins') -%], [% ttlink('Template::Provider', 'Template::Provider') -%], [% ttlink('Template::Service', 'Template::Service') -%], [% ttlink('Template::Stash', 'Template::Stash') -%]

[%- END %]