#!/usr/bin/perl -wT#### HTML template using nested TMPL_LOOPs
##usestrict;
useHTML::Template;
# Send the obligatory Content-Type HTTP header field to the browser.
print"Content-type: text/html\n\n";
my$template = HTML::Template->new(filename => 'loop-nested.tmpl.html');
# A couple of arrays of data to put in a loop:
my@husbands = qw(Abraham Apollo Olof Achilles José Luis);
my@wives = qw(Mary Hyacinth Lisbet Patroclus Sonsoles);
my@no_of_children = qw(4 1 3 0 2);
my@children = qw(Robert Edward William Thomas Discus Joakim Mårten Mattias Laura Alba);
my@loop_data = (); # initialize an array to hold your loop
while (@husbandsand@wives)
{
my%row_data; # get a fresh hash for the row data
# Fill in this row
$row_data{HUSBAND} = shift@husbands;
$row_data{WIFE} = shift@wives;
$row_data{NO_OF_CHILDREN} = shift@no_of_children;
# Here goes the inner loop data
my@inner_loop_data = (); # initialize an array to hold your loop
for (my$i = 0; $i < $row_data{NO_OF_CHILDREN}; $i++)
{
my%nested_row_data; # get a fresh hash for the nested row data
$nested_row_data{CHILD} = shift@children;
# The crucial step - push a reference to this row into the inner loop!
push(@inner_loop_data, \%nested_row_data);
}
$row_data{INNER_LOOP} = \@inner_loop_data;
# The crucial step - push a reference to this row into the loop!
push(@loop_data, \%row_data);
}
# finally, assign the loop data to the loop param, again with a reference:
$template->param(NESTED_LOOP => \@loop_data);
# print the template
print $template->output;
The template (loop.tmpl.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><title>Example with nested TMPL_LOOPs</title></head><body><h1>Example with nested TMPL_LOOPs</h1><TMPL_LOOP NAME="NESTED_LOOP"><div style="padding-left: 20px">
Husband: <TMPL_VAR NAME="HUSBAND"><br><TMPL_IF "NO_OF_CHILDREN">
Wife: <TMPL_VAR NAME="WIFE"><br><TMPL_ELSE>
Husband: <TMPL_VAR NAME="WIFE"><br></TMPL_IF>
Children: <TMPL_VAR NAME="NO_OF_CHILDREN"><br></div><TMPL_IF "NO_OF_CHILDREN"><divstyle="padding-left: 50px">
Name:<br><TMPL_LOOP NAME="INNER_LOOP"><divstyle="padding-left: 30px"><TMPL_VAR NAME="CHILD"><br></div></TMPL_LOOP></div></TMPL_IF><br></TMPL_LOOP></body></html>
The output:
Husband: Abraham
Wife: Mary
Children: 4
Name:
Robert
Edward
William
Thomas
Husband: Apollo
Wife: Hyacinth
Children: 1
Name:
Discus
Husband: Olof
Wife: Lisbet
Children: 3
Name:
Joakim
M�rten
Mattias
Husband: Achilles
Husband: Patroclus
Children: 0
Husband: Jos� Luis
Wife: Sonsoles
Children: 2
Name:
Laura
Alba