现在我们来做个建议的模版引擎
先建一个MySmarty类
<?php
class MySmarty{
public $config = array(
'template_dir' =>'./template',
'compile_dir' =>'./compile',
);
public $arr = array();//
public function __construct()
{
//这里可以定义一个配置类然后导入,这里就不做了
}
//传参方法
public function assign($content,$replacment=null)
{
//以键值对的形式
if($content!=null)
{
$this->arr[$content] = $replacment;
}
}
//显示方法
public function display($tp)
{
$tempfile = $this->config['template_dir']."/".$tp.".html";
if(!file_exists($tempfile))
{
exit("没有模版");
}
$newfile = $this->config['compile_dir']."/com_".md5($tp).".php";
$tplContent=$this->con_replace(file_get_contents($tempfile));//将smarty标签替换为php的标签
file_put_contents($newfile,$tplContent);
//显示编译后的内容
include $newfile;
}
function con_replace($content)
{
//替换<{$data}>的形式的内容,这里外标签可用配置文件代替
$pattern = array(
'/<{s*$([a-zA-Z_][a-zA-Z_0-9]*)s*}>/i'
);
$replacement = array(
'<?php echo $this->arr["${1}"] ?>'
);
return preg_replace($pattern,$replacement,$content);
}
}
?>
然后是程序代码:
<?php
include "./mysmarty.php";
$title="深入浅出之Smarty模板引擎工作机制";
$content="Smarty模板引擎工作机制流程图";
$auth="xwq";
$website="http://xia406413214.web-107.com";
$tpl= new MySmarty();
$tpl->assign("title",$title);
$tpl->assign("content",$content);
$tpl->assign("auth",$auth);
$tpl->assign("website",$website);
$tpl->display("cs");
?>
最后定制模版就可以了
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><{$title}></title>
</head>
<body>
<p>内容:<{$content}></p>
<p>作者:<{$auth}></p>
<p>网址:<{$website}></p>
</body>
</html>
OK简单的模版引擎就好了,接下来我会慢慢完善代码。