您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
酒不醉人人自醉!!mini版smarty模板引擎
发布时间:2016-03-05 09:22:15编辑:雪饮阅读()
哈哈说什么模板引擎,听起来高大上,还不就是正则表达式的原理。。。不过正则表达式也算是php中重难点之一了。
MyMiniSmarty类:
<?php
class MyMiniSmarty{
//模板文件路径
public $template_dir="./templates/";
//替换之后的缓存路径
public $complie_dir="./templates_c/";
//assign分配的数组
public $tpl_vars=array();
//定义assign方法
function assign($tpl_vars,$val=null){
if($tpl_vars!=""){
$this->tpl_vars[$tpl_vars]=$val;
}
}
//定义display方法
function display($tpl_file){
$tpl_file_path=$this->template_dir.$tpl_file;
$complie_file_path=$this->complie_dir."com_intro.tpl.php";
if(!file_exists($complie_file_path)||filemtime($tpl_file_path)>filemtime($complie_file_path)){
$tpl_file_con=file_get_contents($tpl_file_path);//取出模板文件内容
$pattern=array('/\{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*\}/i');//匹配模板变量正则形如{$aaA_cC9},用数组形式正则替换可以将assign所分配的变量数组中所有变量都替换为对应的模板变量中调用出来的值
$replace=array('<?php echo $this->tpl_vars["${1}"]?>');
//替换后的正则匹配,{1}匹配正则模式中第一个{}的值
$new_str=preg_replace($pattern,$replace,$tpl_file_con);
file_put_contents($complie_file_path,$new_str);
//引入编译后文件
include $complie_file_path;
}
}
}
?>
控制器:
<?php
require_once "MyMiniSmarty.class.php";
$MySmarty=new MyMiniSmarty;
$MySmarty->assign("title","我的标题");
$MySmarty->assign("content","我的内容");
$MySmarty->display("intro.tpl");
?>
模板:
<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<head>
<title>模板页</title>
</head>
{$title}<br/>{$content}
</html>
案例源码:
关键字词:mini,smarty,模板引擎