in reply to Methods in template toolkit

Just a matter of style: I don't think it's a good idea to do database lookups in the templates.

That's what the controller (in an MVC approach; the calling script otherwise) is for.

You use a template system because you want to separate program logic and layout - but database calls are surely not a layout technique.

Replies are listed 'Best First'.
Re^2: Methods in template toolkit
by stvn (Monsignor) on Dec 06, 2007 at 18:10 UTC

    I disagree (partially), what the OP is doing here is just grabbing a related object, which is not much different from grabbing a value from a local field. I do agree that the code to fetch from the resultset and such should probably not be in the View, but I would probably put this into the Model rather then the Controller, something like this in his Variant class would work.

    sub get_related_measurement_thingy { my ($self, $type_measurement) = @_; $self->variant_measurements_rs->find( $self->id, $type_measurement->measurement_id ); # the template should probably call ->value though }
    then the OP could improve on it and add error handling or additional validation as well.

    -stvn
      I have actually changed the implementation of this - the call was going through a loop, filling table data cells - many database calls. I now have this:
      sub get_variant_measurements { my $resultset = shift; my $variant_id = @_; my $variant_measurements = $resultset->search_related( 'variant_measurements', { }, { 'order_by' => ['variant_id','measurement_id'] }, ); return $variant_measurements; }
      This is passed to the template, which then does this:
      [% WHILE ( type_measurement = type_measurements.next ) %] <tr> [% WHILE (variant_measurement = variant_measurements.next) %] [% IF variant_measurement.measurement_id == type_measurement.measure +ment_id %] <td> <input type="text" size="3" name="measure-[% variant_measurement.variant_id %]-[% typ +e_measurement.measurement.measurement %]" value="[% variant_measurement.value %]" /> </td> [% END %] [% END %] </tr> [% END %]
      Little hard to work out from the current context, what the db calls done previously in a loop in the template are now carried out in one database call in the handler.