- <?php
- class MyMiniSmarty{
-
- var $template_dir="./templates/";
-
- var $complie_dir="./templates_c";
-
- var $tpl_vars=array();
-
-
-
- function assign($tpl_var,$val=null){
-
- if($tpl_var!=‘‘){
- $this->tpl_vars[$tpl_var]=$var;
- }
- }
-
-
-
- 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)){
-
-
- return false;
-
- }
-
-
- if(!file_exists($comlie_file_path) ||filemtime($tpl_file_path)>filemtime($complie_file_path)){
-
-
- $tpl_file_content=file_get_contents($tpl_file_path);
-
-
-
- $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,$tpl_file_content);
-
-
-
- file_put_contents($complie_file_path,$new_str);
- }
-
-
- include $complie_file_path;
- }
- }
- ?>
注意:对象也可以作为模版变量
案例:
php文件:
$smarty=new Smarty();
$var1=“简单字符串”;
$var2=new 对象名();
$var3=array(内容列表..);
$smarty->assign(“var1”,$var1);
$smarty->assign(“var2”,$var2);
$smarty->assign(“var3”,$var3);
模版文件:
取出 var1 对应的值: {$var1}<br/>
取出 var2 对应的值: {$var2->属性或者方法}
取出 var3 对应的值: {$var3[下标]}
【smarty项目源码】模拟smarty模版文件的解析过程
原文:http://www.cnblogs.com/wangluochong/p/4941504.html