templates/intro.tpl
intro.php
<?php
require_once("MyMinSmarty.class.php");
$mysmarty = new MyMinSmarty;
$mysmarty->assgin("title","我的第一个title");
$mysmarty->assgin("content","我的第一个content");
$mysmarty->display("intro.tpl");
?>
MyMinSmarty.class.php
<?php
class MyMinSmarty{
//定义模板路径
var $template_dir = "./templates/";
//定义编译文件路径
var $complie_dir = "./templates_c/";
//定义存储变量
var $tpl_vars = array();
function assgin($tpl_var,$val=num){//创建一个分配数据的方法,$tpl_var是变量,$val是要分配的值
if($tpl_var!=""){
$this->tpl_vars['$tpl_var']=$val;
}
return 0;}
function display($tpl_file){//创建一个显示数据的方法
$tpl_file_path=$this->template_dir.$tpl_file;//组合模板文件的路径
$complie_file_path=$this->complie_dir."com_".$tpl_file.".php";//组合编译文件的路径
if(!file_exists($tpl_file_path)){//判断模板文件是否存在
echo "文件不存在";
return false;
}
$fpl_file_con=file_get_contents($tpl_file_path);//获取模板文件信息
//echo "文件存在";
$pattern = array(//正则
'/{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*}/i'
);
$replace = array(//要替换的内容
'<?php echo $this->tpl_vars["${1}"] ?>'
);
$new_str = preg_replace($pattern,$replace,$fpl_file_con);
echo $new_str;
file_put_contents($complie_file_path,$new_str);
include $complie_file_path;
}
}
?>