I'm trying to use Mason2 with Dancer and trivial cases like passing string to the template are working fine:
get '/foo', sub {
template 'foo' => {
title => 'bar'
};
};
<%args>
$.title
</%args>
<h1><% $.title %></h1>
So, this is working. Troubles started when I wanted to pass things like hashes or arrays to the template. And when I pass this array to the template:
template 'index', { cats=> [{id=>1,title=>'Cat1'},{id=>2,title=>'Cat2'}]};
And set args in the template to
<%args>
$.cats
</%args>
I cannot loop through this array like this:
<ul>
% foreach my $cat ($.cats){
<li><% $cat %></li>
% }
</ul>
$cat object is the same as $.cats object, an array. I'm not sure what I did wrong.
Thanks.
Borodin is exactly right. $.cats
is an array reference; to loop through the elements, you have to dereference it:
<%args>
$.cats
</%args>
<ul>
% foreach my $cat ( @{$.cats} ) {
<li><% $cat->{title} %></li>
% }
</ul>
Output:
<ul>
<li>Cat1</li>
<li>Cat2</li>
</ul>
Note that <% $cat %>
evaluates $cat
in scalar context and outputs it; since $cat
is a hash reference, this will output something like HASH(0x4b9fad8)
. To output items from the hash, you have to access them by key, e.g. <% $cat->{id} %>
.