[Templates] Order of evaluation

Andrew Beattie andrew@tug.com
Thu, 21 Nov 2002 12:15:28 -0000


21/11/2002 08:42:02, Andy Wardley <abw@andywardley.com> wrote:

>Andrew Beattie wrote:
>> The problem is that the array of hashes(2) isn't evaluated until it's needed.
>
>I'm not sure I follow this bit.  Can you post an example?

no :-(

I've spent an inordinate amount of time trying to build a minimal test case but failed
due to my perl newbieness, so here are the relevant lumps of my code:

The columns are set with:
my $columns = [
   "type",
   "name",
   "device",
   "time"
];

I pass the stuff to TT with

$$vars{'columns'} = $columns;
$$vars{'body'} = \&get_body;

get_body is a function that builds an array of hashes with data from a database

sub get_body {
# get the events which match $select
warn $select;
    my $sth = $dbh->prepare( $select )
        or die "Couldn't prepare statement: " . $select . $dbh->errstr;
    $sth->execute();
    my @aoh;
    my $selectcount = defined($query->param('MAXROWS')) ? $query->param('MAXROWS') : 100 ;
    while ( ($selectcount-- > 0) && (my $hashref = $sth->fetchrow_hashref())){
        push @aoh, { %$hashref };
    }
    $sth->finish;

    removeblanks (\@aoh);
    return mysort (\@aoh);
}

Note that get_body calls removeblanks which takes the unused entries out of $columns.

sub removeblanks {
     my $aoh = shift(@_);
     # take care - don't use a foreach to splice lumps out of it's own array
     my $max_i = scalar(@$columns);
     OUTER: for ( my $i=0; $i<$max_i; $i++ ) {
        $_ = @$columns[$i];
        foreach my $row (@$aoh) {
            next OUTER if ( defined(%$row->{@$columns[$i]}) &&
                %$row->{@$columns[$i]} ne "" );
        }
        # SIDE EFFECT HERE:
        splice(@$columns, $i, 1);
        $i--;
        $max_i--;
    }
    return $aoh
}

In the templates, I include:
1) tablehead: which does a foreach through columns and print *all* the column names
2) tablerow: which does a foreach through the columns to print the body.  This has the
side effect of discarding the unwanted columns
3) tablehead: again, to make a footer.  This one is correct.

Does that make sense?

So the question was:  can I tell TT to evaluate all it's variables before it does
anything, or do I need to explicitly reference them to get them to evaluate?

Andrew