|
I whipped this together for a forum I moderate as a demonstration of HTML::Template code that uses both nested templates AND nested template loops.
Nested Templates
Nested templates allow you to "share" a template (what I call "outer_template.tmpl" in this example) between a bunch of scripts. You then put the output of a specific script ("inner_template.tmpl") into the outer template. This gives you the ability to have a shared look-and-feel among a bunch of HTML::Template scripts.
Nested Loops
Nested TMPL_LOOPs allow you have "loops within loops," very useful for outputting records.
The code:
outer_template.tmpl
<html>
<head>
<title>My Website: <!-- TMPL_VAR TITLE --></title>
</head>
<body>
<img src="my_banner.jpg">
<!-- TMPL_VAR INNER_TEMPLATE_OUTPUT -->
</body>
inner_template.tmpl
<ul>
<!-- TMPL_LOOP CHARACTERS -->
<li> Name: <!-- TMPL_VAR FIRST_NAME -->, <!-- TMPL_VAR LAST_NAME -->
<ul>
<!-- TMPL_LOOP STATISTICS -->
<li><!-- TMPL_VAR STAT_NAME -->: <!-- TMPL_VAR STAT_VALUE --></li>
<!-- /TMPL_LOOP -->
</ul>
</li>
<!-- /TMPL_LOOP -->
</ul>
template_script.pl
#!/usr/bin/perl
use strict;
use CGI qw/:standard/;
use HTML::Template;
my $characters=get_characters();
my $character_list=create_character_list($characters);
fill_outer_template(INNER_TEMPLATE_OUTPUT=>$character_list,TITLE=>'Character List');
################################################################################
sub create_character_list{
my $character_list=shift;
my $inner_template=HTML::Template->new(filename=>'inner_template.tmpl');
$inner_template->param(
CHARACTERS=>$character_list
);
my $inner_template_output=$inner_template->output;
return \$inner_template_output;
}
########################################
################################################################################
sub fill_outer_template{
my %params=@_;
my $outer_template=HTML::Template->new(filename=>'outer_template.tmpl');
$outer_template->param(
TITLE=>$params{TITLE}||'Default Title',
INNER_TEMPLATE_OUTPUT=>$ { $params{INNER_TEMPLATE_OUTPUT}}||'Default Content',
);
print header();
print $outer_template->output();
}
########################################
################################################################################
sub get_characters{
return [
{
FIRST_NAME=>"Fred",
LAST_NAME=>"Flintstone",
STATISTICS=>[
{
STAT_NAME=>'Weight',
STAT_VALUE=>'Too much'
},
{
STAT_NAME=>'Attitude',
STAT_VALUE=>'Cranky'
},
{
STAT_NAME=>'Attractiveness',
STAT_VALUE=>'Butt-Ugly'
},
]
},
{
FIRST_NAME=>"Barney",
LAST_NAME=>"Rubble",
STATISTICS=>[
{
STAT_NAME=>'Weight',
STAT_VALUE=>'Medium'
},
{
STAT_NAME=>'Attitude',
STAT_VALUE=>'Clueless'
},
{
STAT_NAME=>'Attractiveness',
STAT_VALUE=>'Better than Fred'
},
]
},
{
FIRST_NAME=>"Pebbles",
LAST_NAME=>"Flintstone",
STATISTICS=>[
{
STAT_NAME=>'Weight',
STAT_VALUE=>'30 lbs.'
},
{
STAT_NAME=>'Attitude',
STAT_VALUE=>'Child-like'
},
{
STAT_NAME=>'Attractiveness',
STAT_VALUE=>'Cute'
},
]
}
];
}
########################################
|