Part of the website consists of articles. 3k articles are divided into 120 subjects and the subjects into 9 categores. We want a page displaying all the subjects. Each subject would be a link to a list of articles.

Africa: Congo, Darfur, Egypt etc.
Americas: Argentia, Bolivia, Brazil etc.
and so on.

We need an outer loop for each category and within that inner, nested loops for each subject. HTML::Template can handle this very nicely. It needs a reference to an array of hash refs and each hash ref to also contain an array of hash refs. While this can be a bit daunting at first I've found that the DBI module combined with some map trickery can help make it less painful.

We use two SQL tables:

The template:
<html> <head> <title>subjects</title> </head> <body> <h1>subjects</h1> <TMPL_LOOP NAME=category_loop> <h2><TMPL_VAR NAME=category_name></h2> <p> <TMPL_LOOP NAME=subject_loop> <a href="map.cgi?id=<TMPL_VAR NAME=subject_id>"> <TMPL_VAR NAME=subject_name> </a> </TMPL_LOOP> <p> </TMPL_LOOP> </body> </html>
The code:
#!/bin/perl5 use strict; use warnings; use Data::Dumper; use DBI; use HTML::Template; $|++; my $dbh = DBI->connect( "DBI:mysql:database=map;host=localhost", "", "", {RaiseError => 1} ); my $t = HTML::Template->new( filename => 'subjects_tmpl.html', ); # my $category_loop = get_category_loop(); # die Dumper $category_loop; $t->param( category_loop => get_category_loop() ); open my $fh, '>', 'subjects.html' or die "can't open to write: $!\n"; print $fh $t->output; close $fh; sub get_category_loop{ my $sql_category = q{ SELECT category_id, category_name FROM category ORDER BY category_id }; my $sql_subject = q{ SELECT subject_id, subject_name FROM subject WHERE category_id = ? ORDER BY subject_name }; my $sth_subject = $dbh->prepare($sql_subject); return [ map{add_subject_loop($sth_subject, $_)} @{$dbh->selectall_arrayref($sql_category, {Slice => {}})} ]; } sub add_subject_loop{ my ($sth, $category_loop) = @_; $sth->execute($category_loop->{category_id}); $category_loop->{subject_loop} = $sth->fetchall_arrayref({}); delete $category_loop->{category_id}; # not used by the tmpl return $category_loop; }
Points to note are that both
$dbh->selectall_arrayref($sql_category, {Slice => {}})
and
$sth->fetchall_arrayref({})
return an array of hashrefs, the keys being the field names which, happily, is what we have used in the template. The dbh method is used in the former because it is only called once. The statement method is used for the subjects because it is prepared once but executed, in this case, 9 times.

Further,

return [ map{add_subject_loop($sth_subject, $_)} @{$dbh->selectall_arrayref($sql_category, {Slice => {}})} ];
takes advantage of map being very useful when transforming a data structure. For each hash ref returned by selectall_arrayref a function is called which adds another AoH to it (the loop for the subjects). If the debugging lines are uncommented in the script Data::Dumper outputs: (extract):
$VAR1 = [ { 'subject_loop' => [ { 'subject_id' => '2', 'subject_name' => 'africa' }, { 'subject_id' => '101', 'subject_name' => 'congo' }, 'category_name' => 'africa' }, { 'subject_loop' => [ { 'subject_id' => '10', 'subject_name' => 'argentina' }, { 'subject_id' => '11', 'subject_name' => 'bolivia' }, { 'subject_id' => '12', 'subject_name' => 'brazil' }, 'category_name' => 'americas' },
The AoHoAoH that we needed.

An extract from the ouput: (some whitespace removed)

<html> <head> <title>subjects</title> </head> <body> <h1>subjects</h1> <h2>africa</h2> <p> <a href="map.cgi?id=2">africa</a> <a href="map.cgi?id=101">congo</a> <a href="map.cgi?id=118">darfur</a> <a href="map.cgi?id=3">egypt</a> <a href="map.cgi?id=4">kenya</a> <a href="map.cgi?id=100">liberia</a> <a href="map.cgi?id=5">nigeria</a> <a href="map.cgi?id=6">rwanda</a> <a href="map.cgi?id=7">south africa</a> <a href="map.cgi?id=8">sudan</a> <a href="map.cgi?id=9">zimbabwe</a> <p> <h2>americas</h2> <p> <a href="map.cgi?id=10">argentina</a> <a href="map.cgi?id=11">bolivia</a> <a href="map.cgi?id=12">brazil</a> <a href="map.cgi?id=13">canada</a> <a href="map.cgi?id=14">chile</a> <a href="map.cgi?id=15">columbia</a> <a href="map.cgi?id=16">cuba</a> <a href="map.cgi?id=17">ecuador</a> <a href="map.cgi?id=18">haiti</a> <a href="map.cgi?id=97">latin america</a> <a href="map.cgi?id=19">mexico</a> <a href="map.cgi?id=20">peru</a> <a href="map.cgi?id=21">us</a> <a href="map.cgi?id=22">venezuela</a> <p> </body> </html>
I've been using two flat file dbs to do this and it was quite a tricky bit of code that was hard to maintain. MySQL has been pressed into service partly because it was available (on my m/c and the hoster) but mainly due to this being part of a bigger project, a front end.

My initial attempts used one select statement to get all the data in one gulp but I found myself in as many difficulties as with the flat files. DBIs ability to return just the right structure for HTML::Template took me in the direction described.

What do you think? Criticisms and comments welcomed.

Three cheers for HTML::Template, DBI and map.

Obligatory caveat: other templating modules are available.

Update: Added the debug statements mentioned in the text


In reply to HTML::Template nested loops, DBI/MySQL and map by wfsp

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.