我的第一个smarty类:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
class MyTpl{
/*
声明属性$template_dir,保存文档文件所在路径
声明属性compile_dir,保存编译后文件所在路径
*/
//$template_dir = './templates';
//$compile_dir = './template_s';
public $template_dir;
public $compile_dir;
public $tpl_vars;
/*
public private protected
*/
public function __construct($template_dir = './templates',$compile_dir = './template_s'){
//$this作用:指向本对象的属性
$this->template_dir=rtrim($template_dir,'/').'/';
$this->compile_dir =rtrim($compile_dir.'/').'/';
$this->tpl_vars = array();
}
/*
如何实现将php文件声明的变量,分配到html(tpl)文件
assgin()
需要参数$tpl_var,$value
$tpl_var:出现在模板文件(*html/*tpl)中变量的名称
$value----模板文件中对应的变量的值,来自php文件
*/
function assign($tpl_var,$value=null){
if($tpl_var!=""){
$this->tpl_vars[$tpl_var]=$value;
}
}
/*
display("模板文件名")
*第一步:从模板文件中获取<{}>结构
*第二步:替换成<?php ?>语法
$content----整个模板文件
功能:从指定的模板文件中获取所有的<{}>结构,全部替换成<?php ?>
*/
function tpl_replace($content){
//preg_replace(正则表达式,替换成,被替换对象)
//preg_replace();
//定义模板文件中<{}>结构的正则表达式
$pattern = '/\<\{\s*\$([a-zA-Z_\x7f-\xff][0-9a-zA-Z_\x7f-\xff]*)\s*\}\>/i';
//替换成:<?php ? >格式
$replacement= '<?php echo $this->tpl_vars["${1}"]; ?>';
$repcontent = preg_replace($pattern,$replacement,$content);
return $repcontent;
}
//将tpl_replace方法里返回的新文件保存到编译后的templates_s下
//$filename--*.html或者*.tpl
function display($fileName){
$tplFile = $this->template_dir.$fileName;
$repcontent = $this->tpl_replace(file_get_contents($tplFile));
$comFileName = $this->compile_dir."com_".basename($tplFile).".php";
$handle = fopen($comFileName,"w+");
fwrite($handle,$repcontent);
fclose($handle);
include($comFileName);
}
}
?>