primus has asked for the wisdom of the Perl Monks concerning the following question:

hail monks! i am using HTML::Template and i have a question regarding the usage... i am trying to display different tables in a database, and for each table the numbers of columns are different. what i want to do is display each database table in a html table, but since i have to declare
<TMPL_LOOP NAME = "dbase_tbl"> <TMPL_VAR NAME = "column1"> <TMPL_VAR NAME = "column2"> <TMPL_VAR NAME + = "column3"> </TMPL_LOOP>
but what if the database table has more than 3 columns... is there a way to do this TMPL_VAR on the fly... and also the NAME attribute will have to be generated on the fly to match the hash references in the dbase_tbl array.

Replies are listed 'Best First'.
Re: HTML::Template question
by tachyon (Chancellor) on Jan 03, 2003 at 04:18 UTC

    Why not just do it like this:

    <TMPL_LOOP NAME = "dbase_tbl"> <TMPL_VAR NAME = "row"> </TMPL_LOOP> # and in the perl just do my @cols = $sth->fetchrow_array; my $row = join "\n", '<tr>', (map { " <td>$_</td>" } @cols) , "</tr>\ +n"; # now just insert $row on block

    Sure you have moved a little bit of HTML into your code but is saves heaps of typing and handles any width table automatically.

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

(jeffa) Re: HTML::Template question
by jeffa (Bishop) on Jan 03, 2003 at 02:31 UTC
Re: HTML::Template question
by pfaut (Priest) on Jan 03, 2003 at 02:13 UTC

    If you are just too lazy to type in all those <tmpl_var name="xxx"> that you need (it can be tedious given a large table), you could probably write a script to generate that section of the template. Given a list of field names which can be typed in or retrieved from your database, it should only take a few lines of code to generate the necessary template information.

    If, on the other hand, you don't know beforehand what tables you will be accessing or what columns they will contain, then you're out of luck. You'll have to generate the HTML dynamically, probably with CGI.

    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';
Re: HTML::Template question
by shotgunefx (Parson) on Jan 03, 2003 at 05:10 UTC
    Assuming that you columns will always be the same width in a given table and your data is in an AoA (from fetchall_arrayref of similar), you could do...
    # Map the data into cols parameter. my @rows = map { cols=>$_ } @{$datafromquery}; # Later $template->param(rows=>\@rows); <!-- the template --> <tmpl_loop name="rows"> <tr> <tmpl_loop name="cols"> <td><tmpl_var name="value"></td> </tmpl_loop> </tr> </tmpl_loop>

    update
    fixed typo. dws++

    -Lee

    "To be civilized is to deny one's nature."