Search code examples
perltemplate-toolkitdancer

perl dancer: foreach in template is only printing first value


I have what should be a really simple problem in Dancer: I have an array of names, and I'd like to print each one in a template. These names come from an outside source (not a database). However, when I try to do a foreach over the list in the template, I only get the first value.

Code:

use Dancer;
use Template;

set 'template' => 'template_toolkit';

get '/' => sub {
    my @list = ("one","two","three");
    template 'list.tt', {
            'values' => @list,
    };
};
dance;

And template:

<ul>
    <%FOREACH item IN values %>
        <li><% item %></li>
    <%END%>
</ul>

This only outputs a list with a single item, "one". What am I missing?


Solution

  • The expression 'values' => @list expands to a list that contains "values" "one" "two" "three", so you should try with a reference to the array instead:

    template 'list.tt', {
            'values' => [@list],
    };
    

    The above still copies @list and returns a reference. If you want to fetch a reference to the already existing array, use \@list.