[Templates] Re: Array to hash with 1 result

Bill Ward bill@wards.net
Mon, 9 Jul 2007 11:09:10 -0700


You could add new methods to your object that return refs.  So if you have

sub function
{ .... return @something }

then you could create an additional subroutine:

sub function_ref
{
    my $self = shift;
    my @something = $self->function(@_);
    \@something;
}

Use the latter in your templates.

On 7/9/07, Ryan Blomberg <rb@eventful.com> wrote:
> Sergey and Cees,
>
> Sergey, I am using 2.18 as well.. but discovered why it is happening.
>
> Due to perl not being strong typed a subroutine can return whatever
> it wants (scalar,hash,array,reference).
>
> TT tries to guess what was returned so that is in the correct context
> by doing the following:
>
> my @return = &function(@args);
>
> if(scalar(@return) > 1) {
>         assume array of stuff
> } else {
>         return $return[0];
> }
>
> It does that because doing the following would break things:
>
> my $return = &function(@args); (would only get first key or first
> element if an array or hash is returned)
>
> But, doing it this way means they make a guess in the case of arrays
> and hashes that yields my issue.
>
> As Cees explained.. the best way to fix this is to always return
> references or scalars from your subs and never arrays or hashes.
>
> We return arrays and hashes in more places than I would like to admit
> though so we will probably just avoid calling object subroutines in
> templates.
>
> rb
>
> I am using 2.18 as well.
>
> On Jul 7, 2007, at 6:33 AM, Sergey Martynoff wrote:
>
> >
> >> 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 and dumping the result of the function yields $VAR1
> >> = { name => 'test' } instead of the expected $VAR1 = [ { name =>
> >> 'test' } ]
> >
> > You are probably using an older version of Template Tookit. I
> > recall that
> > there was such a problem formerly, but I cannot repeat this bug on
> > TT 2.18.
> >
> >
> > --
> > Sergey Martynoff
> >
> >
> > _______________________________________________
> > templates mailing list
> > templates@template-toolkit.org
> > http://lists.template-toolkit.org/mailman/listinfo/templates
> >
>
>
> _______________________________________________
> templates mailing list
> templates@template-toolkit.org
> http://lists.template-toolkit.org/mailman/listinfo/templates
>


-- 
Help bring back the San Jose Earthquakes - http://www.soccersiliconvalley.com/