Search code examples
perltemplate-toolkit

Perl Template Toolkit: get root variable


short version of question:

is there any way to get the $var-hash (not its subvars) from the template that is given to the process-call

my $tt = Template->new({
    VARIABLES => {
        version => 3.14,
        release => 'Sahara',
    },  
});

my $vars = {
    serial_no => 271828,
    i => 0
    c => 1
};

$tt->process('myfile', $vars);

long version:

from templates point of view serial_no, i and c are global variables but i would like to have also access to it via their parent hash.

Background is that we transfer an xml into an hash-tree. different (independent) templates work on different parts (on different levels) of that tree. A subtemplate gathers some additional informations about parts of that tree. Now i would like to use the subtemplate in a template on this but some template work on one node of the tree

example

A
+-Bs
  +- b1
     +- i
     +- c
  +- b2
     +- i
     +- c
  +- b3
     +- i
     +- c

This tree is transformed into a hash and directly given as $vars Template TA works whole hash (template sees variable Bs) Template TB works on a B-Node and only gets this node (template sees i anc c)

i want to write a BLOCK that takes a B-Node and manipulates it. This block should be usable from TA and TB so iam searching a way to get the complete environment without changing the generator-script.


Solution

  • use a [% PERL %] block or use Template::Plugin::Stash

    tested

    [% USE Stash %]
    [% USE Dumper Indent = 1%]
    <pre>[% Dumper.dump_html( Stash.stash() ) %]</pre>
    

    untested

    [% PERL %]
    $stash->set( iamthestash => $stash ); ## or call your tree thing
    [% END %]