wfsp has asked for the wisdom of the Perl Monks concerning the following question:

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

Replies are listed 'Best First'.
Re: HTML::Template nested loops, DBI/MySQL and map
by rhesa (Vicar) on Nov 14, 2006 at 13:43 UTC
    I think it looks pretty good. Your use of DBI, its shortcut methods (selectall_arrayref and fetchall_arrayref), and the Slice options is spot-on: this is exactly why these methods are there.

    I only have some stylistic comments, prompted by the fact that add_subject_loop modifies one of its arguments.

    1. I would try to remove the side-effects, and make it a proper function
    2. I would try to move the sql strings and the preparation of the subject handle out of get_category_loop
    I believe that would improve the structure of your program, and increase its maintainability. Abstracting away the lower-level sql stuff is a good idea. See for instance Perl Hacks for some pointers.

    I'm also a big fan of prepare_cached, since it can remove the need of global $sth variables.

    Here's a suggested refactoring:

    sub get_category_loop { return [ map { $_->{subject_loop} = get_subject_loop( delete $_->{category_id} ); # dele +te returns the value that was in the hash $_ } @{ $dbh->selectall_arrayref(sql_category(), {Slice => {}}) } ]; } sub get_subject_loop { my $category_id = shift; my $sth = $dbh->prepare_cached( sql_subject() ); $sth->execute($category_id); return $sth->fetchall_arrayref({}); } sub sql_category { return q{ SELECT category_id, category_name FROM category ORDER BY category_id }; } sub sql_subject { return q{ SELECT subject_id, subject_name FROM subject WHERE category_id = ? ORDER BY subject_name }; }
    I'm not so sure anymore if the map is justified. I feel a foreach loop would probably be easier to read now.
      Many thanks for your comments and suggestions. I have taken them all on board.

      I was going to ask about passing the statement handle around - it didn't feel right. Neatly solved.

      I also agree that a for loop is now easier to read than the map. Again, many thanks.

      sub get_category_loop { my @cat_loop_hrefs = @{ $dbh->selectall_arrayref( sql_category(), {Slice => {}} ) }; for my $cat_href (@cat_loop_hrefs){ $cat_href->{subject_loop} = get_subject_loop(delete $cat_href->{category_id}); } return [@cat_loop_hrefs]; }
Re: HTML::Template nested loops, DBI/MySQL and map
by bradcathey (Prior) on Mar 17, 2010 at 20:11 UTC

    Another way to do it, though not as slick, but more readable, IMHO:

    my $stmt = 'SELECT title, id FROM stages_stage ORDER BY id'; my $stages = $dbh->selectall_arrayref($stmt, {Slice => {}}); $stmt = 'SELECT title, stage_id FROM stages_topic ORDER BY stage_id'; my $topics = $dbh->selectall_arrayref($stmt, {Slice => {}}); for my $i ( 0 .. $#$stages ) { $list->[$i]{'stage_title'} = $stages->[$i]{'title'}; $ictr = 0; while ( $topics->[$tctr]{'stage_id'} == $stages->[$i]{'id'} ) { $list->[$i]{'topics'}->[$ictr]{'topic_title'} = $topics->[$tctr] +{'title'}; $tctr++; $ictr++; } } Dumper: $VAR1 = [ { 'stage_title' => 'Visualize Your Life', 'topics' => [ { 'topic_title' => 'Your Mind' }, { 'topic_title' => 'Your Identity' }, { 'topic_title' => 'Your Security' } ] }, { 'stage_title' => 'Choose Your Buyer', 'topics' => [ { 'topic_title' => 'Yourself' }, { 'topic_title' => 'Employee(s)' }, { 'topic_title' => 'Co-Owner' }, { 'topic_title' => 'Family' }, { 'topic_title' => 'Third-Party' } ] }, ];

    —Brad
    "The important work of moving the world forward does not wait to be done by perfect men." George Eliot