in reply to Trying to understand template-foo
I use HTML::Template because its simple and fast and easy for designers to understand. I think the key about doing templates is rather than think of them as code that controls your formatting, think of them as a formatted page where you can control the content.
To help you along here's a simple example that could be used for your wine website
my @rows = (); # H::T can create a looping structure out of # an array of hashes # the keys for each hash are the variable # names for each row of the loop # add database stuff here while(my $ref = $sth->fetchrow_hashref()) { # you can mangle whats in ref, I often # just push the ref onto the array and try to # put my already mangled stuff in the database # This only works though if the variable names in # the template are the same as your DB column names push(@rows,$ref); } my $template = HTML::Template->new(filename=>'/path/to/some.tmpl'); # H::T expects a reference to the array $template->param(wines=>\@rows); # print your header (CGI or CGI::Simple is still useful for this) print $cgi->header(); # and then your H::T output print $template->output();
Then in your template file, assuming you have wine_name, bottles and country ... it might look something like this:
<table cellspacing="3" cellpadding="3" border="1"> <tr> <td><b>Wine</b></td> <td><b>Country</b></td> <td><b>Bottles</b></td> </tr> <tmpl_loop name=wines> <tr> <td><tmpl_var name=wine_name></td> <td><tmpl_var name=country></td> <td><tmpl_var name=bottles></td> </tr> </tmpl_loop> </table>
Your Perl code will add a new row for each element in your @rows array with each of the variable names as <td> areas. There's tons of other stuff useful for doing things like changing the background color for every other row, etc. Have a look at the loop_context_vars option in the H::T docs for that.
I hope that gives you an idea of how to do it.
Lobster Aliens Are attacking the world!
|
|---|