ivo Welch ivo Welch - 3 months ago 10
Perl Question

Template.pm : accessing passed hash in [% perl %]

I know how to access my passed hash in the Template.pm mini-language, but how do I access it in [% PERL %] fragments? I am missing the obvious.

%vars = ( perldefined => "abc", somehash => { a => 'aa', b => 'bb' } );
$template = Template->new( { INTERPOLATE => 1, EVAL_PERL => 1} );


and now some examples

$in1 = 'a plain variables "[% perldefined %]". a hashcontent variable "[% somehash.a %]". good.bye'."\n";
($template->process( \$in1, \%vars )) or die "bad";


works.

print "\niterating over Hash in Template code\n";
$in1 = 'a plain variables [% perldefined %]. a hashcontent variable [% FOREACH key IN somehash.keys %] [% key %] => [% somehash.$key %] [% END %] good.bye..'."\n";
($template->process( \$in1, \%vars )) or die "bad";


works.

print "\nHash print\n";
$in1 = 'a plain variables [% perldefined %]. [% somehash %] ] good.bye.'."\n";
($template->process( \$in1, \%vars )) or die "bad";


works. prints the hash reference.

and now where I am stuck:

print "\nHash print in Perl subcode, lack of knowledge making iterating impossible \n";
$in1 = 'a plain variables [% perldefined %]. [% PERL %] print somehash [% END %] good.bye.'."\n";
($template->process( \$in1, \%vars )) or warn "huh?";


I need to know how to get this so that I can iterate over the hash keys and do other things. probably trivially obvious answer, but I have tried all I could think of and failed.

Answer

The documentation for [% PERL %] is pretty clear.

Perl code is evaluated in the Template::Perl package. The $context package variable contains a reference to the current Template::Context object. This can be used to access the functionality of the Template Toolkit to process other templates, load plugins, filters, etc. See Template::Context for further details.

[% PERL %]
    print $context->include('myfile');
[% END %]

The $stash variable contains a reference to the top-level stash object which manages template variables. Through this, variable values can be retrieved and updated. See Template::Stash for further details.

[% PERL %]
   $stash->set(foo => 'bar');
   print "foo value: ", $stash->get('foo');
[% END %]

So,

$ tpage --eval_perl --define a=4 --define b=5 <<<'
   [%- PERL -%]
      print($stash->get("a"), "\n");
      print($stash->get("b"), "\n");
   [%- END -%]
'
4
5

From the documentation of ::Stash, it sounds like it's safe to treat $stash like a hash.

$ tpage --eval_perl --define a=4 --define b=5 <<<'
   [%- PERL -%]
      print("$stash->{a}\n");
      print("$stash->{b}\n");
   [%- END -%]
'
4
5

(Note that $stash contains more than the contents of %vars.)