perl dancer: passing database info to template
Posted
by
Bubnoff
on Stack Overflow
See other posts from Stack Overflow
or by Bubnoff
Published on 2011-01-15T03:44:36Z
Indexed on
2011/01/15
3:54 UTC
Read the original article
Hit count: 310
Following Dancer tutorial here:
http://search.cpan.org/dist/Dancer/lib/Dancer/Tutorial.pod
I'm using my own sqlite3 database with this schema
CREATE TABLE if not exists location (location_code TEXT PRIMARY KEY, name TEXT, stations INTEGER);
CREATE TABLE if not exists session (id INTEGER PRIMARY KEY, date TEXT, sessions INTEGER, location_code TEXT, FOREIGN KEY(location_code) REFERENCES location(location_code));
My dancer code ( helloWorld.pm ) for the database:
package helloWorld;
use Dancer;
use DBI;
use File::Spec;
use File::Slurp;
use Template;
our $VERSION = '0.1';
set 'template' => 'template_toolkit';
set 'logger' => 'console';
my $base_dir = qq(/home/automation/scripts/Area51/perl/dancer);
# database crap
sub connect_db {
my $db = qw(/home/automation/scripts/Area51/perl/dancer/sessions.sqlite);
my $dbh = DBI->connect("dbi:SQLite:dbname=$db", "", "",
{ RaiseError => 1, AutoCommit => 1 });
return $dbh;
}
sub init_db {
my $db = connect_db();
my $file = qq($base_dir/schema.sql);
my $schema = read_file($file);
$db->do($schema) or die $db->errstr;
}
get '/' => sub {
my $branch_code = qq(BPT);
my $dbh = connect_db();
my $sql = q(SELECT * FROM session);
my $sth = $dbh->prepare($sql) or die $dbh->errstr;
$sth->execute or die $dbh->errstr;
my $key_field = q(id);
template 'show_entries.tt', {
'branch' => $branch_code,
'data' => $sth->fetchall_hashref($key_field),
};
};
init_db();
true;
Tried the example template on the site, doesn't work.
<% FOREACH id IN data.keys.nsort %>
<li>Date is: <% data.$id.sessions %> </li>
<% END %>
Produces page but with no data. How do I troubleshoot this as no clues come up in the console/cli?
Thanks
Bubnoff
© Stack Overflow or respective owner