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;


In reply to Re: HTML::Template: Howto make a inner/outer loop? by gryphon
in thread HTML::Template: Howto make a inner/outer loop? by grath

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.