您现在的位置: 365建站网 > 365文章 > PHP模板技术初探

PHP模板技术初探

文章来源:365jz.com     点击数:1450    更新时间:2009-10-04 11:11   参与评论

在我们使用PHP做网页的时候

希望美工和程序分离出来

而不是将PHP代码嵌入到HTML代码中

下面结合我在网上找的一些资料

(参见 http://blog.csdn.net/leedotnet/archive/2006/07/12/907895.aspx)

给个代码看看

我的工作添加了一个数组的模板导入函数

//希望对大家有用

//这里的template就相当于smart的template类

//index.php 模板类定义和数据初始化文件

<?php
class template
{
 var $content;

 function template($filename)
 {
 //加载文件
 //if(!file_exists($filename));
  $fs = fopen($filename,"r");
  $this -> content = fread($fs, filesize($filename));
  fclose($fs);
 }
 
 function repl($html_rep,$php_rep)
 {
 
  $this -> content = ereg_replace("\{".$html_rep."\}",$php_rep,$this -> content);
 } 
 
 //将变量名当做一个字符串传进来 根据字符串获取变量的值 并生产模板 
 function myrep($varname)
 {
  global $$varname;
  $php_rep=$$varname;
  $this -> content = ereg_replace("\{".$varname."\}",$php_rep,$this -> content);
 }
 
 function rep_array($array_data)
 {
  global $$array_data;
  $data=$$array_data;

  $num=count($data);
  for($i=0;$i<$num;$i++)
  {
   $php_rep=$data[$i];
   $this -> content = ereg_replace("\{".$array_data."\[$i\]"."\}",$php_rep,$this -> content);
  } 
 } 
 
 function out()
 {
  echo $this -> content;
 }
}//class

//使用方法
 $html = new template("show.html");
 //变量的写法
 // <title>{title}</title>
 //$html -> repl("subject","文字");//旧的方法
 //$html -> repl("content","内容");
 $list[]="1";
 $list[]="2";
 $list[]="3";
 $list[]="4";
 $title="文字";
 $data="内容";
 
 $html->rep_array("list");//导入数组
 $html->myrep("title");//导入变量

 $html->myrep("data"); 
 $html -> out();
?>

//show.html 模板文件 只有HTML代码

<html>
<head>
<title>{title}</title>
<body>
{data}
<br \>
<ul>
<li>{list[0]}</li>
<li>{list[1]}</li>
<li>{list[2]}</li>
<li>{list[3]}</li>
</ul>
</body>
</head>
</html>

这样当我们浏览index.php的时候,就能够将INDEX.PHP的数据导入到模板文件show.html中显示

如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (1450人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号