in reply to div in cgi
Using CGI.pm's helpers to generate your output is nothing short of unwieldy. Sure, it works, and it's Perl, and you end up with mostly well-formed HTML, but it's just a lot of work. Use Template::Toolkit instead. There's a little learning curve at first, but then your life becomes easier once you catch on to it.
The code (mycgi.pl):
#!/usr/bin/env perl use strict; use warnings; use CGI; use Template; use FindBin qw($Bin); use constant TEMPLATE_PATH => "$Bin/"; (my $template = __FILE__) =~ s/\.pl$/.tt/; # Derive the template from +the script name. my $data = {list => [qw(foo bar baz)]}; render($template, $data); sub render { my ($temp, $data) = @_; my $t = Template->new({INCLUDE_PATH => TEMPLATE_PATH}) || die "$Template::ERROR\n"; $t->process($temp, $data) || die $t->error, "\n"; }
The template (mycgi.tt):
<!DOCTYPE html> <html> <head> <title>Hello world</title> </head> <body> <ul> [%- FOR string IN list %] <li> <div class inforno /> ----[% string %]---- </div> </li> [%- END %] </ul> </body> </html>
The output:
<!DOCTYPE html> <html> <head> <title>Hello world</title> </head> <body> <ul> <li> <div class inforno /> ----foo---- </div> </li> <li> <div class inforno /> ----bar---- </div> </li> <li> <div class inforno /> ----baz---- </div> </li> </ul> </body> </html>
I see that you've already received recommendations for Template::Toolkit and Mojo::Template.
Here is the same code adapted for Mojo::Template:
use strict; use warnings; use CGI; use Mojo::Template; use FindBin qw($Bin); use constant TEMPLATE_PATH => "$Bin/"; (my $template = __FILE__) =~ s/\.pl$/.tt/; # Derive the template from +the script name my $data = {list => [qw(foo bar baz)]}; render($template, $data); sub render { my ($temp, $data) = @_; print Mojo::Template ->new(vars => 1) ->render_file(TEMPLATE_PATH . $temp, $data); }
And the Mojo::Template based template:
<!DOCTYPE html> <html> <head> <title>Hello world</title> </head> <body> <ul> % for my $string (@$list) { <li> <div class inforno /> ----<%= $string %>---- </div> </li> % } </ul> </body> </html>
The output remains the same. I find Mojo::Template to be pretty simple to use since its tags are based on Perl rather than on a DSL that takes time to learn.
By contrast, let's look at the code to generate similar (but with worse formatting) output using only CGI.pm's helpers.
#!/usr/bin/env perl use strict; use warnings; use CGI qw(:standard); my $data = {list => [qw(foo bar baz)]}; print start_html(-title => "Hello world"); print ul( map{ li( div({class => 'inforno'}, "----$_----") ) . "\n" } @{$data->{'list'}} ); print end_html();
I find that harder to skim through and reason about. We all should be looking for ways to simplify our code in ways that make it easier to reason about, regardless of our level of proficiency.
Dave
|
|---|