Perl (Dancer) & Template Toolkit - looping thru hashref

1.1k views Asked by At

I'm using Perl with Dancer and Template Toolkit.

I'm passing a hashref to my template.

This is the way it's built, out of an array (@musicList):

my $hashrMusic = {};
my $intCount = 0;

foreach my $track ( @musicList ) {
    $hashrMusic->{ $intCount } = $track;
    $intCount++ ;
}

This is the Dumper version of the hash:

 $VAR1 = {
      '1049' => '09 Faruk\'s Funk (Matt Stein + Nickodemus Rework).mp3',
      '127' => '45 There She Goes.mp3',
      '71' => 'Kenny Wayne Shepherd - One Foot On The Pass.mp3'
        };

This is the way I pass the hashref to the template:

template 'scan.tt', {
    'countTracks' => scalar keys %$hashrMusic,
    'tracks' => $hashrMusic,
    'dump' => Dumper($hashrMusic),
}

Now I'm trying to loop through the hasref to display it, using the following TT code:

          <ul>
            <% FOREACH track IN tracks %>
              <li><% track.value %></li>
            <% END %>
          </ul>

This produces no output (but countTracks is OK, just as dump). Any hint/idea?

2

There are 2 answers

0
chilladx On BEST ANSWER

Dancer is not using TemplateToolkit by default, but a look-like template engine that does not support TT tags. Digging in the config files and configuring the template engine to be TT solved the issue.

4
yahermann On

You forgot the closing /li. Also you're misusing FOREACH with respect to hashrefs.

Try this:

 <ul>
   <% FOREACH track IN tracks %>
     <li>
       The key is: <% track.key %>
       The filename is: <% track.value.filename %>
     </li>
   <% END %>
 </ul>

For complete documentation on FOREACH, go here:

http://www.template-toolkit.org/docs/manual/Directives.html#section_FOREACH