开发者

How to easily create tables in the template toolkit View in perl/Catalyst

I am developing an App using Perl's Catalyst framework. In trying to keep presentation logic out of my models I am looking for a way in the VIEW (template toolkit) to generate an HTML table from a given data structure. I currently use HTML::Table::FromDatabase to generate my html tables from SQL queries but this is currently in the Model. 开发者_C百科I am looking to isolate presentation logic to the View rather than have it in the model . Any advice on this would be helpful


This is from memory and just riffing so consider it untested. It’s a simple way to automatically iterate through columns and records.

Assumes a sub something like this with a DBIx::Class based model–

sub some_action : Local Args(0) {
    my ( $self, $c ) = @_;
    my $rs = $c->model("SomeTable")->search({},{rows => 10});
    $c->stash( some_rs => $rs );
}

And then the matching template–

[% records = some_rs.all %]
[% RETURN UNLESS records.size %]
[% columns = records.0.columns %]
<table>
  <tr>
  [% FOR column IN columns %]
    <th>[% column | ucfirst | html %]</th>
  [% END %]
  </tr>

  [% FOR item IN records %]
  <tr>
    [% FOR column IN columns %]
      <td>[% item.${column} | html %]</td>
    [% END %]
  </tr>
  [% END %]
</table>


I pass the data structure (as an array of hashes) into TT and just use TT logic to build the table, with CSS classes to control the look of the table.

Simplified example of the template:

  <table class="ixTable">
    [% FOREACH listing = listings %]
    <tr class="ixRow">
      <td class="ixAddress">[% listing.address %]</a></td>
      <td class="ixPrice">[% listing.listprice %]</td>
      <td class="ixSqFt">[% listing.sqft %]</td>
    </tr>
    [% END %]
  </table>


Good ol' CGI.pm makes this not too difficult, but to get any real help you are going to have to show what your data structure looks like.

One potential issue is that your data may be in hashes that by their nature don't provide a column order (though database purists will tell you HTML::Table::FromDatabase is wicked and bad for encouraging select * and assuming column order is meaningful).

HTML::Table::FromDatabase itself uses HTML::Table; you might see if that meets your needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜