在使用smarty模板的时候刚开始总是觉得很是神奇,因为只要我们写一个模板文件,后缀名可以使任意的但是必须是放在templates的目录下,然后新建一个PHP文件,调用smarty引擎文件,然后就可以很方便地进行操作。其实在底层是smarty设计者进行了封装。把模板文件进行获取,然后在底层进行处理,最后在templatas_c文件夹下生成一个PHP文件,这个文件才是真正要执行的展示给用户的。
在对模板进行处理的时候其实用到了正则表达式的相关知识的。所以对此方面的知识还是得有一定的了解。这个有助于自己了解底层运行方式
<?php
//Smarty模板中有一个核心文件Smarty.class.php 这个就是最最核心的模板引擎
//由专业php程序员开发.
class MyMiniSmarty {
var $template_dir="./templates/";
var $compile_dir="./templates_c/";
var $tpl_vars=array();
public function assign($tpl_var, $value=null){
if($tpl_var!="")
$this->tpl_vars[$tpl_var]=$value;
}
public function display($fileName){
$tplFile=$this->template_dir.$fileName;
if(!file_exists($tplFile)){
return false;
}
$comFileName=$this->compile_dir."com_".$fileName.".php";
if(!file_exists($comFileName) || filemtime($comFileName) < filemtime($tplFile)){
$repContent=$this->tpl_replace(file_get_contents($tplFile));
file_put_contents($comFileName, $repContent);
}
include $comFileName;
}
//这里需要使用到这则表达式的知识
private function tpl_replace($content){
$pattern=array(
'/\<\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}\>/i'
);
$replacement=array(
'<?php echo $this->tpl_vars["${1}"]; ?>'
);
$repContent=preg_replace($pattern, $replacement, $content);
return $repContent;
}
}
?>
<?php
//新建一个PHP文件并使用自己设计的模板引擎
require_once 'MyMiniSmarty.class.php';
$myTemplate=new MyMiniSmarty();
$myTemplate->assign("title","知识共享平台,有好的文章大家共享");
$myTemplate->assign("intro","让我们一起加油吧");
$myTemplate->display("temp.tpl");
?>