MyMiniSmarty.class.php
View Code
1 tpl_vars[$tpl_var] = $var;19 }20 }21 //替换占位符编译成可运行文件22 function display($tpl_file) {23 $tpl_file_path = $this->template_dir . $tpl_file;24 $complie_file_path = $this->compile_dir . 'com_' . $tpl_file . '.php';25 if (!file_exists($tpl_file_path)) {26 return false;27 }28 //判断是否有缓存文件,以前编译过,检查模板文件和编译文件修改时间29 if (!file_exists($complie_file_path) || filemtime($tpl_file_path) > filemtime($complie_file_path)) {30 $fpl_file_con = file_get_contents($tpl_file_path);31 32 //核心是正则替换33 34 $pattern = array(35 '/\{\s*\$([a-zA-Z_]\w*)\s*\}/i'36 );37 $replace = array(38 ' tpl_vars["${1}"] ?>' 39 );40 41 $new_str = preg_replace($pattern, $replace, $fpl_file_con);42 43 file_put_contents($complie_file_path, $new_str);44 }45 46 47 48 49 //引用编译后的文件50 include($complie_file_path);51 }52 53 }54 ?>
intro.php
View Code
assign('title', '模板标题'); $mysmarty->assign('content', '模板内容'); $mysmarty->display('intro.tpl');?>
intro.tpl
View Code
{$title} {$content}
模板机制在于,简单标签代替php代码,使逻辑代码和页面设计分离,同时加入文件缓存等机制