smarty自定义引擎模板

自定义smarty类

<?php

//定义类MyTpl

class MyTpl{

//定义变量

public $template_dir='./templates/';
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:需要和模板中的变量名对应

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结构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);
}
}
?>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值