thomas895 has asked for the wisdom of the Perl Monks concerning the following question:

Maybe I'm looking in all the wrong places, but I can't seem to figure out how to access the stash ref from a Template plugin.
For example:

sub new { my( $class, $context ) = @_; #Stash my $stash = $context->{'STASH'} or die( "No stash given" ); #Bless object ref my $self = bless( { CONTEXT => $context, DBH => $stash->get('DBH') }, $class ); return $self; }

...dies as if the stash does not exist. However, when I get a dump of the @_ array, it does appear:

'STASH' => bless( { #...megabytes of data omitted for brevity }, 'Template::Stash' );

However, the docs state in Template::Plugin that the second argument(including the class name) is a Template::Context object, which contains the stash. And the dump above includes a full stash.
I have tried the following as well:

my $stash = $context->stash; #Returns a TT2 undef error "Can't call me +thod "stash" on an undefined value"

So my question is:

  1. How do I access the stash from a plugin?
  2. Why can't I access the stash like I am now?

~Thomas~

Replies are listed 'Best First'.
Re: Stash access for a Template::Plugin plugin
by Anonymous Monk on Jan 02, 2012 at 04:30 UTC

    How do I access the stash from a plugin?

    Use the accessor  $context->stash as documented?

    Why can't I access the stash like I am now?

    I'm guessing (because your snippet isn't demonstrative) that by the time you try to access it, it probably doesn't exist anymore :)

    Does Template::Plugin::Stash work for you?

    $ cat stash.tt [% USE Stash %] [% USE Dumper Indent = 1 %] [% Dumper.dump( Stash.stash() ) %] $ tpage --define foo=bar stash.tt $VAR1 = { 'global' => {}, 'foo' => 'bar' };
Re: Stash access for a Template::Plugin plugin
by Khen1950fx (Canon) on Jan 02, 2012 at 05:53 UTC
    FWIW, I've never used a stash before, so my sympathies:). I tried this. Maybe it'll help.
    package MyPlugin; use base qw( Template::Plugin ); use strict 'refs'; use warnings; sub load { my ($class, $context) = @_; bless { _CONTEXT => $context, }, $class; } sub new { my( $class, $context, $dsn ) = @_; return $class->error('no stash given') unless $dsn; bless { _DSN => $dsn, }, $class; } package main; use strict 'refs'; use warnings; use Template::Stash; use Data::Dumper::Concise; my $stash = Template::Stash->new({ var1 => 'value1', var2 => 'value2'} +); print "var1 => ", Dumper( $stash->get( 'var1' ) ); print "var2 => ", Dumper( $stash->get( 'var2' ) );