自定义smarty类
<?php
//定义类MyTpl
class MyTpl{
//定义变量
public $compile_dir='./templates_c/';
public $tpl_vars;
function __construct($template_dir='./templates/',$compile_dir='./templates_c'){
$this->template_dir=rtrim($template_dir,'/').'/';
$this->compile_dir=rtrim($compile_dir,'/').'/';
$this->tpl_vars=array();
}
//需要两个参数$tpl_var,$value
//$tpl_var---模板文件中变量的名称
//$value---模板文件中变量的值。来自于php文件
//调用该方法是用来分配给模板中对应的变量
//参数$tpl_var:需要和模板中的变量名对应
if($tpl_var!=''){
$this->tpl_vars[$tpl_var]=$value;
}
}
/*
实现模板的调用
display(文件名)
*/
//从模板文件中获取<{ $titlename}>结构
/*
提换成<?php echo $titlename?>
*/
//$content----整个模板文件
//功能:从指定的模板文件中获取所有<{ $titlename}>结构全部替换成<?php echo //$titlename结构mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit] )
function tpl_replace($content){
/*
preg_replace ( 正则表达式n, 替换成, 被替换成内容 )
定义:模板文件中<{$title}>结构的正则表达式
*/
$pattern='/\<\{\s*\$([a-zA-Z_\x7f-\xff][0-9a-zA-Z_\x7f-\xff]*)\s*\}\>/i';
//替换后:<?php echo <h4>title</h4>
//本文件中保存变量采取$this->tpl_vars[title]=$value;
$replacement='<?php echo $this->tpl_vars["${1}"]; ?> ';
//替换后返回新的html文件
$repcontent=preg_replace($pattern,$replacement,$content);
return $repcontent;
//将tpl_replace方法里返回的新文件保存在templates_c下
//$fileNamw---*.html 或者*.tpl*
}
function display($fileName){
//$this->template_dir="./templates";
//$filaName="a.html"
//$this->template_dir.$filaName=./templates/a.html'
$tplFile=$this->template_dir.$fileName;
$repcontent=$this->tpl_replace(file_get_contents($tplFile));
//将该编译后文件保存到templates_c里 com_**/php
//将编译后的文件保存到templates_c basename(path,suffix)
$comFileName=$this->compile_dir."com_".basename($tplFile).".php";
//将变量$repcontent 写入到com_a.php
$handle=fopen($comFileName,"w+");
fwrite($handle,$repcontent);
fclose($handle);
include($comFileName);
}
}
?>