[Templates] Stuck on getting data from a nested hash.

Lesley Binks lesley.binks@zen.co.uk
Thu, 17 Aug 2006 21:21:05 +0100


Hello

I'm a bit stuck on hashes at the moment.

Sorry if this question has been asked before but I have the following 
hash set up in a perl script


     %menu = (
          "Home" => {url => "./", name =>"Home",},
          "Contact" => {url => "./contact.php", name=>"Contact",},
     );

I create a reference to a hash thus :

      my $vars = {
             ...
             head => \%const_head,
             sitemenu => \%menu,
             ...
           };
and pass it to a Template object via

     $tt->process($tmpl_file,$vars,$html_file) || die "Can't pwocess 
this!!";

where the Template object has already been successfully instantiated.

In my templates, stuff like

  <base href="[% head.baseurl%]" />

runs correctly but I cannot get
        <div id="menu">
                   [% sitemenu %]
                  [% FOREACH item IN sitemenu %]
                   [% item %]
                  <a href="[% sitemenu.item.url %]">[% 
sitemenu.item.name %]</a>&nbsp;&nbsp;
                 [% END %]

to print out the name and url elements of each hash in sitemenu.

The value output for [% sitemenu %] is  HASH(0x82d90f8) which matches 
that output by the perl script when I print out all layers of that data. 
  So [% sitemenu %] appears to be pointing to the right bit of memory.

Values for [% item %] (and incidentally [% sitemenu.item %]) are 
HASH(0x84c3c6c) and then HASH(0x84c3c9c).

Values from the perl script are dumped via this code in the perl script
    my $sitemenu = \%menu;
       print "\n\n".$sitemenu."\n";
       foreach my $frd (keys %$sitemenu) {
          print $frd."\t".$sitemenu->{$frd}."\t";
          foreach my $frd2 (keys %{$sitemenu->{$frd}}) {
             print "\n\t\t".$frd2." :: ".$sitemenu->{$frd}->{$frd2};
          }
          print "\n";
       }
and give these results :
HASH(0x82d90f8)
Contact HASH(0x82e0cf4)
                 name :: Contact
                 url :: ./contact.php
Home    HASH(0x82e0c70)
                 name :: Home
                 url :: ./
)

So the hashes for the elements of the menu hash are not the same.
I get no output for [% sitemenu.item.url %] and [% sitemenu.item.name %].

I get the same result whether I use sitemenu.item.name or item.name (and 
likewise for the url component) in that template code.  The loop 
iterates but produces no output for the menu components I need.

Can anyone spot the error I'm making?

Hope you can help

Regards

Lesley Binks