PHP模板引擎很多,但要么很庞大,要么效率很低,如果只是要实现PHP代码与程序分离,就只要一个简单的模板引擎就行了。今天抽空写了一个。
xt.class.php
<?php
/*
* Created on 2011-10-08
* @author xyl
* This is simple template engine for your site
*/
class XT{
var $folder="template";//模板文件目录
var $t_type=".html";//模板文件类型
var $data=array();
var $subtp=array();//字模板
var $t_cache="./tcache";//模板缓存目录
var $compile=false;//调试
var $content_path="";
function XT(){
if(!file_exists($this->t_cache)){
mkdir($this->t_cache) or die("Failed to create cache directory:".$this->t_cache);
}
}
function setdata($k,$v){
$this->data[$k]=$v;
}
function subtemplate($filename){
if(is_array($filename)){
foreach($filename as $v){
$this->parse($v);
}
}else{
$this->parse($filename);
}
}
function __parsedata($content){
//模板包含
$this->subtp=array();
preg_match_all("/<!--\s+include\((.+)\)\s+-->/iu",$content,$rt);
if(!empty($rt[1][0])){
foreach($rt[1] as $v){
if(!empty($v)){
$this->subtp[$v]=$v;
}
}
if(!empty($this->subtp)){
$this->subtemplate($this->subtp,true);
}
}
$content = preg_replace("/<!--\s+include\((.+)\)\s+-->/iu", "<?php include('$this->t_cache/\\1.php');?>", $content);
//变量
$content = preg_replace("/\{(\\\$[a-z0-9_]+)\}/s", "<?=\\1?>", $content);
//逻辑
$content = preg_replace("/<!--\s+if\((.+)\):\s+-->/iu", "<?php if(\\1) { ?>", $content);
$content = preg_replace("/<!--\s+endif\s+-->/iu", "<?php } ?>", $content);
//循环
$content = preg_replace("/<!--\s+foreach\((.+)\):\s+-->/iu", "<?php foreach(\\1) { ?>", $content);
$content = preg_replace("/<!--\s+endforeach\s+-->/iu", "<?php } ?>", $content);
return $content;
}
function parse($filename=null,$sub=false){
$filename=(empty($filename)?basename($_SERVER["PHP_SELF"],".php"):$filename);
$content_path=$this->t_cache."/".$filename.".php";
if(!file_exists($content_path)||$this->compile){
$content=implode("",file($this->folder.'/'.$filename.$this->t_type));
$content=$this->__parsedata($content);
file_put_contents($content_path,$content);
}
!$sub?$this->content_path=$content_path:'';
}
function out(){
extract($this->data);
include_once($this->content_path);
}
}
?>
用法:
test.php
<?php
/*
* Created on 2011-9-29
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
include("xt.class.php");
$title="测试";
$content="内容";
$footer="底部";
$arr=array("a","b");
$xt=new XT();
//通过setdata方法赋值给模板
$xt->setdata('title',$title);
$xt->setdata('content',$content);
$xt->setdata('arr',$arr);
$xt->setdata('chk',true);
//调试模板开启,正式用时关闭,默认是关闭的
$xt->compile=true;
//编译模板,模板文件默认与当前页面同名,如当前文件为test.php,模板文件则对应于template/test.html
$xt->parse();
//输出内容
$xt->out();
?>
test.html
<html>
<head>{$title}</head>
<body>
<!-- include(header) -->
{$content}
<!-- if($chk): -->
{$content}
<!-- endif -->
<!-- foreach($arr as $k=>$v): -->
{$v}
<!-- endforeach -->
<!-- include(footer) -->
</body>
</html>