php学习笔记(三十三)php自定义模板引擎的实现
2013-01-06 16:32
627 查看
自己实现简单的模板引擎:方面php的逻辑与页面进行分离
模板类:
调用的页面:
转换页面:
模板类:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><{$title}></title> </head> <body> <{$content}> </body> </html>
调用的页面:
<?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"); ?>
转换页面:
<?php 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)<filemtime($tplfile)) { $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('/\<{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}\>/i'); $replacement = array('<?php echo $this->tpl_vars["${1}"]; ?>'); $repContent = preg_replace($pattern, $replacement, $content); return $repContent; } } ?>
相关文章推荐
- php学习笔记-3.thinkphp表的join和模板引擎输出
- PHP学习笔记三十三【自定义错误处理器】
- 自定义属性之图片切换实例——初始化、实现切换效果——JS学习笔记2015-5-29(第42天)
- 学习笔记之 自定义连接池实现代码
- PHP学习笔记【21】--PHP实现文件下载
- PHP学习笔记:利用百度api实现手机归属地查询
- php实现简单视图模板(视图引擎)
- php学习笔记(四十)smarty3的模板继承新特性
- php学习笔记:利用gd库生成图片,并实现随机验证码
- zabbix3.2学习笔记(六):自定义监控nginx+php-fpm status
- ((ios开发学习笔记 十二))Nib加载的方式实现自定义TableView
- 强大的DataGrid组件[9]_自定义头模板(HeaderTemplate)——Silverlight学习笔记[17]
- 韩顺平_PHP程序员玩转算法公开课(第一季)07_使用数组实现堆栈_学习笔记_源代码图解_PPT文档整理
- torch学习笔记3.2:实现自定义模块(cpu)
- PHP学习笔记——自定义函数中的返回值(return);
- 对比JAVA学习PHP系列:高级:PHP的模板引擎Smarty
- 【学习笔记】PHP实现页面静态化
- PHP学习笔记 第七讲 PHP函数和自定义函数
- PHP学习笔记【18】--PHP防盗链实现
- 关于SQLServer2005的学习笔记——自定义分组的实现