[Templates] reiterating thru hashes of hashes: How? template side

Mark Fowler mark@twoshortplanks.com
Tue, 19 Nov 2002 10:29:10 +0000 (GMT)


On Mon, 18 Nov 2002, JustSome person wrote:

> How do I itterate over a hash of hashes?

>From the FAQ:

=item How to do I itterate over a hash?

This is covered in the VMethods section of the manual page.  A list of all
the keys that are in the hash can be obtained with the 'keys' virtual
method.  You can then itterate over that list and by looking up each key
in turn get the value.

    [% FOREACH key = product.keys %]
       [% key %] => [% product.$key %]
    [% END %]

(not from faq from this point on...should I add it?)

So, we can get the value for each 'key' by doing hashname.$key ... This
lets us do:

[%

flintstones = { fred   => { wife => "wilma", child => "pebbles" },
                barney => { wife => "betty", child => "bambam"  } };

"<ul>";

# for each of the keys of the main hash (fred, barney...)
FOREACH subhashkey = flintstones.keys;

 # print a <li> to start this hash
 "<li>";
 subhashkey;
 "<dl>";

 # itterate though the keys of the hash that that subkeypoints at
 # i.e. "wife", "child"
 innerhash = flintstones.$subhashkey;
 FOREACH finalkey = innerhash.keys;

  "<dt>"; finalkey;            "</dt>";  # a key of inner hash
  "<dd>"; innerhash.$finalkey; "</dd>";  # a value of the inner hash

 END;

 "</dl></li>";

END;

"</ul>";

%]

Mark.

-- 
s''  Mark Fowler                                     London.pm   Bath.pm
     http://www.twoshortplanks.com/              mark@twoshortplanks.com
';use Term'Cap;$t=Tgetent Term'Cap{};print$t->Tputs(cl);for$w(split/  +/
){for(0..30){$|=print$t->Tgoto(cm,$_,$y)." $w";select$k,$k,$k,.03}$y+=2}