template简介
时间:2005-11-01 来源:含笑汉
最初Perl对CGI的处理是直接调用cgi模块,然后逐句输出,如下例所示:
#!/usr/bin/perl
use strict;
use CGI;
my $query = new CGI;
print $query->header;
print $query->start_html(-title=>"show hello");
print "
";
print "hello,world!!";
print "";
print $query->end_html;
exit(0);
这样的写法对于程序员来说可能只是工作量的问题,而对于web设计人员来说,这样的开发几乎是不可想象的。
Template模块将web系统的表现层和业务逻辑层分开,这样就使得程序开发人员和web设计人员能够专注于自己的工作。
Template模块定义了一系列的标签,web设计者只需要将那些动态内容用这些标签进行描述就可以。而程序员可以使用Template模块读出html页面的内容并对其中的动态标签进行赋值或转换,然后所有的内容返还给用户,显示在浏览器中。
下面举一个例子:
首先我们制作一个含有动态和静态的模版页面hello.html,代码如下:
[% title %]
Hello World!
© Copyright [% year %] [% author %]
然后使用Template读取hello.html文件并对其中的变量赋值,并输出。
Template.pl
use Template;
my ($type) = "text/html; charset=gbk";
print "Content-type: ", $type, " ";
my $config = {
INCLUDE_PATH => 'C:/tmp',
EVAL_PERL => 1,
};
my $template = Template->new($config);
my $author="Arthur Dent";
my $title="Greet the Planet";
my $bgcol="#FF6600";
my $year=2003;
my $vars = {
author => $author,
title => $title,
bgcol => $bgcol,
year => $year,
};
my $temp_file = 'hello.html';
my $output;
$template->process($temp_file, $vars, $output)
|| die $template->error();
print $output;