[Templates] Comparing foo.first

Bill Moseley moseley@hank.org
Thu, 17 Aug 2006 06:47:35 -0700


On Thu, Aug 17, 2006 at 09:22:40AM -0400, Garrett, Philip (MAN-Corporate) wrote:
> Bill Moseley wrote:
> > Must be time to quit for the day as this doesn't make sense, and I'm
> > sure it's very obvious.
> > 
> > I have template code that generates <th> elements based on a passed
> > in array.  I set class tag on the <th> to indicate if it's a first,
> > middle or last column.
> > 
> > So, something like:
> > 
> >     FOR column = headers;
> > 
> >         col_pos = column == headers.first
> >             ? 'first'
> >             : column == headers.last
> >                 ? 'last'
> >                 : 'middle';
> > 
> >         "<th class='$col_pos'>";
> > 
> >         [...]
> > 
> > which has been working find.  A added a new page today and noticed
> > that the first column was <th class='middle'>.
> 
>     <th class="[% loop.first ? "first" : loop.last ? "last" : "middle"

Yes, that's the right way.  Thanks.



Now, I'm just curious what's happening.  If I modify the 'first'
vmethod in Template::Stash:

        'first'   => sub {
            my $list = shift;
    warn "list is [$list] and first element is [$list->[0]]\n";
            return $list->[0] unless @_;
            return [ @$list[0..$_[0]-1] ];
        },

Then do this in my template:

    "headers = [$headers] and first element is [$headers.0]\n" | stderr;
    first_element = headers.first;
    "First = [$first_element]\n" | stderr;


        FOR column = headers;
        ...

I see this:

So the list is changing when the vmethod is called.

    headers = [ARRAY(0xa5cd210)] and first element is [ARRAY(0xa5a5768)]
    list is [ARRAY(0xa5c5098)] and first element is [ARRAY(0xa5c5284)]
    First = [ARRAY(0xa5c5284)]

Deep clone???


Viewing another page that uses this template I see what I'd expect:

    headers = [ARRAY(0xa95d1f4)] and first element is [ARRAY(0xa95d314)]
    list is [ARRAY(0xa95d1f4)] and first element is [ARRAY(0xa95d314)]
    First = [ARRAY(0xa95d314)]


Time for coffee.

-- 
Bill Moseley
moseley@hank.org