use Template::Store; my $store = Template::Store->new( directory => '/tmp/tt3/store', extension => '.ttc', ); # set() method to store Perl code in a file $store->set( foo => $foo_perl_code ); # get() method to require() it back in again $foo_object = $store->get('foo') || die "foo is not in store\n";
The Template::Store module implements a simple filesystem-based store, providing persistant storage of compiled templates. It also acts as a base class for other storage modules that store templates using different media or mechanisms.
The Template::Store is a little like the Template::Cache module. Both are designed to save us from having to compile a template from source code into Perl code whenever possible, given that this is the most time consuming part of processing a template. The key difference between them is that the Template::Cache module stores live Perl objects in memory, whereas Template::Store saves the compiled Perl code on disk (or some other storage system). However, both return live Perl objects, from their get() method. In the case of Template::Store, the file in which the component Perl code is stored is loaded using Perl's require() function, causing the Perl code to be loaded and evaluated into a Template::Component object.
Constructor method used to create a new store module. The
directory argument (or
dir for short) must be provided to define
the root directory under which compiled template files should be
use Template::Store; my $store = Template::Store->new( directory => '/tmp/tt3/store' );
ext for short) parameter can be
used to define an extension that will be automatically added to the
end of the name of each file used to store compiled templates.
my $store = Template::Store->new( directory => '/tmp/tt3/store' extension => 'ttc' );
If the extension begins with a word character, as shown in the
previous example, then it will be added to the end of the filename
. character used to delimit them (e.g. ".ttc"). If the
extension already begins with a non-word character (e.g. ".ttc",
"-ttc", etc) then it is appended as it is with no further delimiter
Public method to store the Perl code generated for a compiled template
based on a unique identifier. The
$perl_code argument should be
provided as a scalar or reference to a scalar.
my $perl_code = $compiler->compile($source_code); $store->set( foo => $perl_code );
Public method to fetch an item from the store if it exists. The unique identifier is passed as the first argument. The method loads the relevant file associated with the identifier using Perl's require(), thereby evaluating the Perl code and generating a Template::Component object (or whatever other result the Perl code returned).
my $foo = $store->get('foo') || die "foo not in store";
Any errors raised by the Template::Store module will be thrown as
Template::Exception objects with a
store type. This includes
errors in the
new() constructor (e.g. no
set() methods (e.g. failed to read or write a file).