用PHP制作静态网站的模板框架(四)
2024-05-04 23:01:13
供稿:网友
 
本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。静态网站的模板框架 
   首先,我们象前面一样为所有的页面公用元素以及页面整体布局编写模板文件;然后从所有的页面删除公共部分,只留下页面内容;接下来再在每个页面中加上三行php代码,如下所示: 
<?php 
<!-- home.php --> 
<?php require('prepend.php'); ?> 
<?php pagestart('home'); ?> 
<h1>你好</h1> 
<p>欢迎访问</p> 
<img src="http://edu.cnzz.cn/newsinfo/demo.jpg"> 
<p>希望你能够喜欢本网站</p> 
<?php pagefinish(); ?> 
?> 
   这种方法基本上解决了前面提到的各种问题。现在文件里只有三行php代码,而且没有任何一行代码直接涉及到模板,因此要改动这些代码的可能性极小。此外,由于html内容位于php标记之外,所以也不存在特殊字符的处理问题。我们可以很容易地将这三行php代码加入到所有静态html页面中。 
   require函数引入了一个php文件,这个文件包含了所有必需的与模板相关的php代码。其中pagestart函数设置模板对象以及页面标题,pagefinish函数解析模板然后生成结果发送给浏览器。 
   这是如何实现的呢?为什么在调用pagefinish函数之前文件中的html不会发送给浏览器?答案就在于php 4的一个新功能,这个功能允许把输出到浏览器的内容截获到缓冲区之中。让我们来看看prepend.php的具体代码: 
<?php 
require('class.fasttemplate.php'); 
function pagestart($title = '') { 
global $tpl; 
$tpl = new fasttemplate('.'); 
$tpl->define( array( 'main' => 'main.htm', 
'header' => 'header.htm', 
'leftnav'=> 'leftnav.htm' ) ); 
$tpl->assign('title', $title); 
ob_start(); 
} 
function pagefinish() { 
global $tpl; 
$content = ob_get_contents(); 
ob_end_clean(); 
$tpl->assign('content', $content); 
$tpl->parse('header', 'header'); 
$tpl->parse('leftnav', 'leftnav'); 
$tpl->parse('main', 'main'); 
$tpl->fastprint('main'); 
} 
?>