mmceldowney has asked for the wisdom of the Perl Monks concerning the following question:
So I'm not new to perl, but I've not used Template::Toolkit before. Yes, for years I have been mixing my code and my html output with print statements. I know, I know, but I'm trying to do the right thing now and move to Template. I'm having difficulty in getting my FOREACH in the template to output my dataset. I must be missing something but I just don't see where my mistake is. If anyone would look this over and provide suggestions it would be greatly appreciated.
My template (sandbox.tt2) code is:
<!DOCTYPE html> <html> <head> <title>Sandbox</title> </head> <body> <ul> [% FOREACH row in rows %] <li>[% row.ams_wac %] - [% row.sitename %]</li> [% END %] </ul> </body> </html>
and my perl code is:
#!/usr/bin/perl -w use strict; use warnings; use v5.26; use CGI; use Template; use DBI; use Data::Dumper; use lib qw(.); require "utils.pl"; my $content = "Content-type: text/html\n\n"; my $template = ''; my $vars = ''; my $conn = ''; my $rows = ''; $conn = dbconnect(); $rows = $conn->selectall_arrayref("select ams_wac, sitename from sites + where active = 'TRUE' order by sitename",{Slice => {}}); $template = Template->new({ INCLUDE_PATH => ['templates'] }); print Dumper($rows); $template->process('sandbox.tt2', {rows => $rows}, \$content) or die $template->error(); dbdisconnect($conn); print $content;
My output is not looping through the dataset:
Content-type: text/html <!DOCTYPE html> <html> <head> <title>Sandbox</title> </head> <body> <ul> </ul> </body> </html>
and Dumper shows I do have data in $rows:
$VAR1 = [ { 'sitename' => 'Site One', 'ams_wac' => 'SLRHC' }, { 'ams_wac' => 'SLR', 'sitename' => 'Site Two' }, { 'sitename' => 'Site Three', 'ams_wac' => 'SLRSIX' } ];
I've got to be missing something simple and I'm sure the answer will reinforce the fact that I'm an idiot. Thanks for any help.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Template Toolkit troubles with looping through database resultset
by ikegami (Patriarch) on Nov 28, 2018 at 06:27 UTC | |
by mmceldowney (Initiate) on Nov 28, 2018 at 16:19 UTC |