php自定义模板引擎,php学习笔记(三十三)php自定义模板引擎的实现

这篇博客介绍了一个简单的PHP模板引擎的实现方法,通过创建MyTpl类实现了模板和逻辑的分离。类中包括了模板路径和编译路径的设置,变量赋值,模板文件的读取、编译和显示等功能,旨在提高代码的可读性和维护性。
摘要由CSDN通过智能技术生成

自己实现简单的模板引擎:方面php的逻辑与页面进行分离

模板类:

调用的页面:

include "mytpl.class.php";

$tpl = new MyTpl("./templates/","./templates_c");

//程序简单方式

$title="这是一个文字标题,从数据库中获取";

$content = "这是内容";

$tpl->assign("title",$title);

$tpl->assign("content",$content);

$tpl->display("mysmarty.html");

?>

转换页面:

header("ContentType=text/html;charset=UTF-8");

class MyTpl{

private $template_dir;

private $compile_dir;

private $tpl_vars=array();

/**

* 模板路径和编译后的路径

* @param 模板路径 $template_dir

* @param 编译路径 $compile_dir

*/

function __construct($template_dir="./templates",$compile_dir="./templates_c"){

//添加最后的/

$this->template_dir = rtrim($template_dir,"/").'/';

$this->compile_dir = rtrim($compile_dir,"/").'/';;

}

/**

* 将变量输入到数组中

* @param unknown_type $tpl_var

* @param unknown_type $value

*/

public function assign($tpl_var,$value=NULL){

if($tpl_var!=""){

$this->tpl_vars[$tpl_var]=$value;

}

}

/**

* 显示最后生成的文件

* @param 模板文件 $fileName

*/

public function display($fileName){

//模板文件

$tplfile = $this->template_dir.$fileName;

if (!file_exists($tplfile)) {

return false;

}

//编译的文件名

$confileName = $this->compile_dir."com_".$fileName.".php";

if (!file_exists($confileName) || filemtime($confileName)

$repContent = $this->tpl_replace(file_get_contents($tplfile));

file_put_contents($confileName, $repContent);

}

//显示输出

include $confileName;

}

/**

* 替换模板后返回

* Enter description here ...

* @param unknown_type $content

*/

private function tpl_replace($content){

//匹配正则表达式

$pattern = array('/\/i');

$replacement = array('<?php echo $this->tpl_vars["${1}"]; ?>');

$repContent = preg_replace($pattern, $replacement, $content);

return $repContent;

}

}

?>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值