On 7/6/07, Ryan Blomberg <[EMAIL PROTECTED]> wrote:
list_things returns and array of hashrefs (1 or more)

my template does the following

[% FOREACH thing IN object.list_things() %]
   The name of the thing is [% thing.name %]
[% END %]

If the function returns

return [ { name => 'test' } ];

I get not output

Actually, I would guess that your output would be one or more lines of
the following:
---
The name of the thing is
---

What is happening is that the FOREACH loop is getting a single hashref
from your call to object.list_things().  If you check the docs for
FOREACH, you will see that if you try to iterate over a hash or
hashref with a FOREACH loop it will loop once for each key in the hash
like so (example taken direct from Template::Manual::Directives):

              [% users = {
                   tom   => 'Thomas',
                   dick  => 'Richard',
                   larry => 'Lawrence',
                 }
              %]

              [% FOREACH u IN users %]
                 * [% u.key %] : [% u.value %]
              [% END %]


The reason you don't see this happening when you return two hashes
from object.list_things() is because template toolkit sees multiple
return values and assumes you want to iterate over an array of values.
But when you return only one hashref, it can not guess that you want
to treat it as a one element list of hashrefs.

To add insult to injury, the normal way of getting around this
limitation is to add an extra .list on the end of your call to tell
template toolkit that you want the single return value to be treaded
as a list, but since object.list_things returns one hashref,
object.list_things.list will call the 'list' vmethod on the hashref,
returning the hashref as a flattened list of values (See
Template::Manual::VMethods for info on calling .list of a hashref).

So the only way to cleanly avoid this problem is to return an arrayref
of hashrefs from object.list_things.  That way it is completely
unambiguous to template toolkit what type of data structure it is
dealing with.

Cheers,

Cees

_______________________________________________
templates mailing list
[email protected]
http://lists.template-toolkit.org/mailman/listinfo/templates

Reply via email to