Search code examples
htmlperlmojolicious

How i can generate number of rows, columns in table using perl loop in mojolicious?


I have a task in mojolicious, i must pass to a template folder the number of rows in html table, in template folder, based on the number of rows, it must generate the necessary amount of rows that i ask, to do it i must use loops. The idea is, i write the number of roes that i want, for example 3, submit, and then the program generates me the correct amount that i want. May be i should use hashes?

My controller:

my @rownum = (1,2,3,4,5);

$self->render("table/tablerow", rownum => \@rownum);

and this is the code in template.

<html>
<head>
<style type="text/css">
TABLE {
 border-collapse: collapse;  
}
TD, TH {
 padding: 10px; 
 border: 1px solid black; 
}
</style>
</head>
<body>
<table>
   <tr><th>Heading 1</th><th>Heading 2</th></tr>
   <tr><td>Cell 1</td><td>Cell 2</td></tr>
</table>
</body>
</html>

Solution

  • Here's an example using a Mojo::Template. I pass the rows in a variable, and I don't care what the count is. Inside the template I simply output something for each element in the list:

    use v5.10;
    use Mojo::Template;
    
    my @rows = (1,2,3,4,5);
    
    my $mt = Mojo::Template->new;
    say $mt->vars(1)->render(<<'EOF', { rows => \@rows } );
    % for (@$rows) {
    <%= "Row $_\n" =%>
    % }
    EOF
    

    There are plenty of other ways to do this with Mojo::Template, too.