Ryan Blomberg wrote:
> I have an object we will call 'object' with an accessor method  
> 'list_things'
> 
> 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 %]

I have a lot of legacy objects that return lists of hashrefs (or scalars
or objects, for that matter), so I've had to figure out a solution for
this myself. I came up with a global function (which I add to every TT
stash along with the instance data) that cleans things up for me. 

  sub as_list {
        return ref($_[0]) eq 'ARRAY' ? shift : [ shift ];
  }

  $tt->process($template, { object => $object, as_list => \&as_list });

  # in $template

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

Since TT will always collapse a plural return value into an arrayref,
you just take any other type of single value and assume that it needs to
be wrapped in an arrayref. I'm sure this could be wrapped in a plugin
somehow, but it works for me like this.

HTH,
Jason

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

Reply via email to