02 May 2011

HTML::Template

ไฟล์ที่เป็น template นั้นจะใส่นามสกุลไว้ว่า .tmpl โดยต้องใช้ HTML::Template โหลดขึ้นมา

<tmpl_var> เป็นการส่งค่ามาแสดงใน template

test.tmpl
<html>
<head>
    <title>Test Template</title>
</head>
<body>

My Home Directory is <tmpl_var name=home>
<br />
My Path is set to <tmpl_var name=path>

</body>
</html>

test.pl
#!c:\perl\bin\perl.exe
use HTML::Template;
use CGI::Carp qw(fatalsToBrowser);

#open html template
my $tmpl = HTML::Template->new(filename => 'tmpl/index.tmpl');

#fill parametors
$tmpl->param(home => $ENV{HOME});
$tmpl->param(path => $ENV{PATH});

#send
print "Content-Type:text/html\n\n",$tmpl->output();

<tmpl_loop> ทำลูปใน template

test.tmpl
<html>
<head>
    <title>Loop Template</title>
</head>
<body>
<tmpl_loop name=emp>
    <tmpl_var name=name> -- <tmpl_var name=job><br>
</tmpl_loop>

<tmpl_loop name=loop2>
    <tmpl_var name=var1> -- <tmpl_var name=var2><br>
</tmpl_loop>
</body>
</html>
test.pl
#!/perl/bin/perl.exe
use HTML::Template;
use CGI::Carp qw(fatalsToBrowser);

my $tmpl = HTML::Template->new(filename=>'tmpl/loop.tmpl');
$tmpl->param(emp => [{name=>'test1',job=>'unknow'},{name=>'test2',job=>'programer'}]);

my @var1 = qw(who am i);
my @var2 = qw(set to me);

my @loop_data = ();

while(@var1 and @var2){
    my %row_data;
    $row_data{var1} = shift @var1;
    $row_data{var2} = shift @var2;
   
    push(@loop_data,\%row_data);
}
$tmpl->param(loop2=>\@loop_data);

print "Content-Type:text/html\n\n";
print $tmpl->output();

<tmpl_include> ดึงเอา template อื่นมา
include.pl
#!/perl/bin/perl
use HTML::Template;
use CGI::Carp qw(fatalsToBrowser);

my $tmpl = HTML::Template->new(filename=>'tmpl/include1.tmpl');

print "Content-Type:text/html\n\n",$tmpl->output();


include1.tmpl
<html>
<head>
    <title>include</title>
</head>
<body>
from include1.tmpl<br>
<tmpl_include name="include2.tmpl">

include2.tmpl
from include2.tmpl
</body>
</html>

0 comments:

Post a Comment