http://qs321.pair.com?node_id=342739


in reply to HTML::Template: Howto make a inner/outer loop?

Greetings grath,

I worship HTML::Template these days, but one of my early learning curve issues was figuring out nested loops. (This was before I actually RTFMed HTML::Template instead of just skimming, though.) Just remember that everything is a hash, and loops are just a bunch (i.e. array) of hashes. When you have a nested loop, it's just an array of hashes that's the value of a key that's part of the outer loop.

The following code is untested and was pulled from your legacy script and modified. This should give you a place from which to get started.

my $query1 = &db_query("SELECT id, title FROM sections"); my @sections = (); while (my $rows1 = $query1->fetchrow_hashref()) { my $sectionid = $rows1->{id}; my $query2 = &db_query("SELECT title FROM pages WHERE sectionid = $s +ectionid"); my @pages = (); while (my $rows2 = $query2->fetchrow_hashref()) { push @pages, $rows2; } push @sections, { pages => \@pages }; } $template->param(sections => \@sections);

I hope this helps. Try using Dump::Dumper to see the created data structure before sending it to HTML::Template. Actually seeing the data structure has helped me on many occations. Also, your legacy script doesn't use strict or use warnings. I recommend you put those in there.

UPDATE: Use jeffa's code from his post. It's far better than mine because he rewrote the database interface using more standard DBI syntax. Use my code above only as a learning tool to map to your original script.

gryphon
code('Perl') || die;