[dancer-users] Database template not working (and also my Dancer2 code)

CHONG Yu Meng yumeng.chong at invictus.com.sg
Sun Jul 2 03:41:38 BST 2017

Hi all, 

Learning Dancer2 and trying to re-learn Perl, so please be patient. 

I've read the Manual and Tutorial, and I can get most examples working, except for querying a database and displaying the results. I am using Dancer2::Plugin::Database.

I have a simple database table (jpstars):
| id | firstname     | lastname           |
|  1 | Harumi         | Nemoto             |
|  2 | Eiko               | Koike                  |
|  3 | Ami               | Ayukawa            |

I have the following Dancer2 code (dancerapp.pm):

package dancerapp;
use Dancer2;
use Dancer2::Plugin::Database;

our $VERSION = '0.1';
get '/dbtest'  => sub {
        my $sth = database->prepare(
                'SELECT id, firstname, lastname FROM jpstars;'
        $sth -> execute;
        template 'display_jpstars', {
                subscribers => $sth -> fetchrow_hashref('id')

I have this template file (display_jpstars.tt)

<tr> <th>First Name</th> <th>Last Name</th> </tr>
<% FOREACH id IN subscribers.keys.nsort %>
<tr> <td><% subscribers.$id.displayname %></td> <td><% subscribers.$id.emailaddr %></td> </tr>
<% END %>


I get an error: "Can't use attribute 'id' because it doesn't contain a reference to an array"

I'm pretty sure my template code is wrong (my dancer.pm code too), but I have no idea how it should look. Help! 

Thanks in advance!

Pascal CHONG

More information about the dancer-users mailing list