首页 > 开发 > PHP > 正文

使用PHP4中的 IntegratedTemplate类实现HTML和PHP代码分离

2024-05-04 22:58:19
字体:
来源:转载
供稿:网友
使用php编程的人都会碰到这样一个问题:当php代码和html代码在一起的时候,看php代码很费劲,整个文件也无法用dreamweaver来编辑,这对于php程序员和美工来讲,修改这样的文件就象一个噩梦。
php中的模板(template)技术就是为了解决这个问题而出现的。php模板类有很多,比较常见的是 fasttemplate 和 phplib, 因为出现得早,在php编程界名声很大。php程序员不知道这两个类,就象vb程序员不知道msgbox函数一样,是一件不可思议的事情。
以前我们需要去下载php模板类,现在php4有了自己的模板类 integratedtemplate 和 integratedtemplateextension,功能和phplib 差不多。这两个类是子类和父类的关系。一般我们用 integratedtemplateextension 就可以了。让人感到不可思议的是 integratedtemplate 不是从 pear 类继承过来,无法用到 pear 类的 debug 功能。
以下举例子说明它们的用法,假设 integratedtemplate 类和 integratedtemplateextension 类分别在 c:/php4/pear/html/itx.php 和 c:/php4/pear/html/itx.php 中。我们写的代码放在c:/testphp/php4/welcome.htm 和 c:/testphp/html/welcome.php 中。将c:/testphp/php4 在web server 上设成虚拟目录 /testphp 并且给与脚本执行权限,确认c:/testphp/html/welcome.htm 无法通过远端浏览器访问。在 php.ini 里面设置 include_path = ".;c:/php4/pear"
例1:
我们在html文件中放置变量的标记,用php代码设置变量的值,然后将html中的标记替换掉,最后输出到客户浏览器。
以下是 welcome.htm 代码,我们放了三个php tag(变量标记)为: {welcometitle}、{username}、{welcomemessage}
<html>
<head>
<title>{welcometitle}</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<style type="text/css">
<!--
body,p,br,div,td,table { font-size: 9pt}
-->
</style>
</head>

<body bgcolor="#ffffff" text="#000000">
<p align="center">您好,{username}</p>
<p align="center">{welcomemessage} </p>
</body>
</html>

以下是welcome.php代码
<?php
require_once "html/itx.php";

//以下是给变量赋值,在实际代码中可能从database中取得数据然后赋值
$welcometitle = "欢迎来到网页天堂";
$username = "皮皮鲁";
$welcomemessage = "您的到来让我们深感荣幸!";

//一般来说这种全局变量放在单独的一个文件中,便于维护
$html_code_file_root = "../html/";

$tpl = new integratedtemplateextension($html_code_file_root);

指定要替换 tag 的 html 文件
$tpl->loadtemplatefile("welcome.htm");

替换html 文件中的 tag
$tpl->setvariable( array (
"welcometitle" => $welcometitle,
"username" =>$username,
"welcomemessage" =>$welcomemessage
) );

输出替换后的 html
$tpl->show();
?>

这样写好后,welcome.htm 仍然可以使用网页编辑器如dreamweaver、frontpage 进行编辑,welcome.php中是纯粹的php代码,不含html,方便以后的代码修改和维护。
如果将 integratedtemplateextension 类和 php4中的 cache 类 联合使用,在速度上可以得到很好的效果。
php4 模板类还可以使用 block,配合其他 php4 中的类 可以很轻松地实现数据库数据检索的翻页,可以很轻松写出论坛之类的软件。

补充说明:为了防止用户直接用 welcome.htm 看网页,将 welcome.htm 放在客户访问不到的目录(只要不在web server 的虚拟目录下即可)。对于大型的php项目,图片、php代码、html文件、多语言字符串文件都应该放在不同的目录,这样在多人共同做一个项目时不至于混乱。

最大的网站源码资源下载站,

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表