On Fri, May 24, 2002 at 03:13:08PM -0500, Shannon, Bryan wrote:
> I would like to share a Stash (Template::Stash::XS) object between two
> distinct Template objects, but am having no luck.

> my $stash = Template::Stash::XS->new();
> my $template_one = Template->new( {STASH => $stash} );
> my $template_two = Template->new( {STASH => $stash} );

That's the right way to do it, but you're being caught out by the
fact that the stash gets localised when you call $template_xxx->process();

So, each template processor ends up with a cloned copy of the same stash.
If you set a variable like 'foo' in one, then it won't show up in the other.
However, if you have a hash defined in the original stash, you can use that
to pass data between processors.  The stash only performs a shallow clone
so although you end up with two different stash hashes, they both contain
references to the same nested hash.  

Here's an example:

#!/usr/bin/perl -w

use strict;
use Template;
use Template::Stash;
my $stash = Template::Stash->new({ 
    foo  => 10, 
    data => { x => 'Hello' },
});
my $tt1 = Template->new({ STASH => $stash });
my $tt2 = Template->new({ STASH => $stash });

local $/ = undef;
my $template = <DATA>;

print "-- #1 --\n";
$tt1->process(\$template)
    || die $tt1->error();

print "-- #2 --\n";
$tt2->process(\$template)
    || die $tt1->error();


__DATA__
foo       : [% foo %]
foo += 10 : [% foo = foo + 10; foo %]
data.x    : [% data.x %]
data.x'   : [% data.x = 'World'; data.x %]


The output is:

-- #1 --
foo       : 10
foo += 10 : 20
data.x    : Hello
data.x'   : World
-- #2 --
foo       : 10
foo += 10 : 20
data.x    : World
data.x'   : World

Notice how the changes to 'foo' aren't propagated, but those to 'data.x'
are.

HTH
A



Reply via email to