smarty 模板

<?php
class MyTpl{
 /*
 声明 $template_dir属性,保存模板文件所在路径
 声明 $compile_dir属性,保存编译后文件所在路径
 */
 
public $template_dir="./templates"; //html
public $compile_dir="./templates_c";//编译后的文件
public  $tpl_vars=array();//获取保存php中变量值
 
 /*
 *public private protected
 *
 * $tpl=new MyTpl("./templates/","./templates_c/");
 *  
 */
public 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();
}


/*
*如何实现将php文件中声明的变量 分配到html(tpl)文件
*   assign()
    需要两个参数$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("模板文件名");
第一步:从模板文件中获取 <{ $titlename }> 结构
第二步:替换成 <?php echo $titlename; ?>  语法
*/


//$content---整个模板文件
//功能:从指定的文件中获取所有<{ $titlename }>结构,全部替换成 <?php echo $titlename;?>  语法
function tpl_replace($content){
/*
 preg_replace();
mixed preg_replace ( 正则表达式, 替换成, 被替换对象)

*/
//定义模板文件中<{$title}> 结构的正则表达式
$pattern = '/<\{\s*\$([a-zA-Z_x7f-\xff][0-9a-zA-Z_x7f-\xff]*)\s*\}\>/i';
 // \,,转义符  \s 任意空白
//替换后的内容<?php echo $titlename; ?>格式
//本文件中保存变量方式 $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下
//$fileName--*.html 或者 *.tpl
function display($fileName){
//$this->template_dir="./fileName";
//$fileName="a.html"
//$this->template_dir.$fileName="teplates/a.html"

 $tplFile=$this->template_dir.$fileName;
 
//file_get_contents()
$repcontent=$this->tpl_replace(file_get_contents($tplFile));

//将该编译后的文件存储到templace_c里com_***。php

//将编译后的文件保存到templace_c
//pathname()  basename()  dirname()  pathinfo()
// ./ templce_c/come_a.php  目前该文件为空
$comFileName = $this->compile_dir."com_".basename($tplFile).".php";

//将变量$repcontent写入到come_a.php文件
$handle=fopen($comFileName,"w+");
fwrite($handle,$repcontent);
fclose($handle);


include($comFileName);


}


}

?>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值