Hi,
I've actually asked this over the mailing list [email protected], not
knowing that there is a mailing list for TT. :p
I'm trying to pickup CGI web application programming using Perl, DBI &
TT (Template Toolkit). This small application is about storing data
(using
CGI::FormBuilder) list it using Template Toolkit. After retrieving
records from MySQL using DBI, I've problem understanding how to pass
to TT, even though I've managed make it work by copy some code from
Perl Mongers & TT's tutorial. Below are my codes :
>>> >>> start of list.cgi <<<
#!/usr/bin/perl
use warnings;
use strict;
#use diagnostics;
use Template;
use DBI;
my %kar;
my $tt_file='list.tt';
my $tt = Template->new({
INCLUDE_PATH => './tt',
}) || die "$Template::ERROR\n";
my $vars = {
kars => \%kar,
};
sub db_select {
my ($dsn,$dbuser,$dbpass,$dbh,$plh_reg_no,$sth,$reg_no,$brand,$cc);
$dsn = "dbi:mysql:database=mycars:hostname=127.0.0.1";
$dbuser = "driver";
$dbpass = "plaintext";
$dbh = DBI->connect($dsn,$dbuser,$dbpass)
or die "cannot connect to database : $DBI::errstr";
$plh_reg_no = "car%";
$sth = $dbh->prepare("SELECT reg_no,brand,CC FROM auto_details WHERE
reg_no like ?");
$sth->execute($plh_reg_no)
or die "Cannot execute statement : $DBI::errstr";
while (($reg_no, $brand, $cc) = $sth->fetchrow_array()) {
$kar{$reg_no} = {
reg_no => $reg_no,
brand => $brand,
cc => $cc
}
}
$dbh->disconnect();
}
db_select();
$tt->process($tt_file, $vars)
|| die "Template process failed: ", $tt->error(), "\n";
>>> >>> end of list.cgi <<<
>>> >>> start of list.tt <<<
Content-type: text/html
[% PROCESS header %]
Form <strong>List</strong>
<p>
<ul>
[% FOREACH kar IN kars.values %]
<li>[% kar.reg_no %], [% kar.brand %], [% kar.cc %]</li>
[% END %]
</ul>
</p>
[% PROCESS footer %]
>>> >>> end of list.tt <<<
Although the above code works as what have expected, but I would like
to know more ways of passing arrays from perl to TT.
My questions :
- can someone show me other then the "while" loop that i used above,
is there other way of extracting data from DBI and passed it to TT?
- also, is there any other way of looping the rows passed from perl in TT?
- I think I've read about some where on some website that arrays
passing to TT should always use array reference
($sth->fetchrow_arrayref) instead of the
above, using arrays ($sth->fetchrow_array). If this were to use array
reference, can someone please show example codes?
Thanks in advance,
Edward.
_______________________________________________
templates mailing list
[email protected]
http://mail.template-toolkit.org/mailman/listinfo/templates