开发者

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?


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.


I'll wager it's because you have to pass an array reference to the 'values':

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

Otherwise the list gets expanded and you're actually passing:

template 'list.tt', {
        'values' => $list[0],
        $list[1] => $list[2],
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜