0

0

Discuz的模板引擎

php中文网

php中文网

发布时间:2016-07-25 09:06:18

|

1612人浏览过

|

来源于php中文网

原创

填写您的邮件地址,订阅我们的精彩内容:

discuz的模板引擎 一个比较好的模板引擎类,很久以前就在网上找到,目测这个discuz的模板引擎应该很老了,是dz7.2以前的版本了,自己也用得很顺手,分享下这个模板类。

有两个文件。一个模板类,一个模板替换中需要用到的函数
原文地址:http://blog.qita.in

Genesis
Genesis

开源的生成式物理引擎,可模拟世界万物。

下载
  1. ?
  2. /**
  3. * 模板类 - 使用 Discuz 模板引擎解析
  4. * http://blog.qita.in
  5. */
  6. require_once (DIR_ROOT . '/../function/template.func.php');
  7. class Template {
  8. const DIR_SEP = DIRECTORY_SEPARATOR;
  9. /**
  10. * 模板实例
  11. *
  12. * @staticvar
  13. * @var object Template
  14. */
  15. protected static $_instance;
  16. /**
  17. * 模板参数信息
  18. *
  19. * @var array
  20. */
  21. protected $_options = array();
  22. /**
  23. * 单件模式调用方法
  24. *
  25. * @static
  26. * @return object Template
  27. */
  28. public static function getInstance() {
  29. if (!self :: $_instance instanceof self)
  30. self :: $_instance = new self();
  31. return self :: $_instance;
  32. }
  33. /**
  34. * 构造方法
  35. *
  36. * @return void
  37. */
  38. private function __construct() {
  39. $this -> _options = array('template_dir' => 'templates' . self :: DIR_SEP, // 模板文件所在目录
  40. 'cache_dir' => 'templates' . self :: DIR_SEP . 'cache' . self :: DIR_SEP, // 缓存文件存放目录
  41. 'auto_update' => false, // 当模板文件改动时是否重新生成缓存
  42. 'cache_lifetime' => 0, // 缓存生命周期(分钟),为 0 表示永久
  43. );
  44. }
  45. /**
  46. * 设定模板参数信息
  47. *
  48. * @param array $options 参数数组
  49. * @return void
  50. */
  51. public function setOptions(array $options) {
  52. foreach ($options as $name => $value)
  53. $this -> set($name, $value);
  54. }
  55. /**
  56. * 设定模板参数
  57. *
  58. * @param string $name 参数名称
  59. * @param mixed $value 参数值
  60. * @return void
  61. */
  62. public function set($name, $value) {
  63. switch ($name) {
  64. case 'template_dir':
  65. $value = $this -> _trimpath($value);
  66. if (!file_exists($value))
  67. $this -> _throwException("未找到指定的模板目录 "$value"");
  68. $this -> _options['template_dir'] = $value;
  69. break;
  70. case 'cache_dir':
  71. $value = $this -> _trimpath($value);
  72. if (!file_exists($value))
  73. $this -> _throwException("未找到指定的缓存目录 "$value"");
  74. $this -> _options['cache_dir'] = $value;
  75. break;
  76. case 'auto_update':
  77. $this -> _options['auto_update'] = (boolean) $value;
  78. break;
  79. case 'cache_lifetime':
  80. $this -> _options['cache_lifetime'] = (float) $value;
  81. break;
  82. default:
  83. $this -> _throwException("未知的模板配置选项 "$name"");
  84. }
  85. }
  86. /**
  87. * 通过魔术方法设定模板参数
  88. *
  89. * @see Template::set()
  90. * @param string $name 参数名称
  91. * @param mixed $value 参数值
  92. * @return void
  93. */
  94. public function __set($name, $value) {
  95. $this -> set($name, $value);
  96. }
  97. /**
  98. * 获取模板文件
  99. *
  100. * @param string $file 模板文件名称
  101. * @return string
  102. */
  103. public function getfile($file) {
  104. $cachefile = $this -> _getCacheFile($file);
  105. if (!file_exists($cachefile))
  106. $this -> cache($file);
  107. return $cachefile;
  108. }
  109. /**
  110. * 检测模板文件是否需要更新缓存
  111. *
  112. * @param string $file 模板文件名称
  113. * @param string $md5data 模板文件 md5 校验信息
  114. * @param integer $md5data 模板文件到期时间校验信息
  115. * @return void
  116. */
  117. public function check($file, $md5data, $expireTime) {
  118. if ($this -> _options['auto_update'] && md5_file($this -> _getTplFile($file)) != $md5data)
  119. $this -> cache($file);
  120. if ($this -> _options['cache_lifetime'] != 0 && (time() - $expireTime >= $this -> _options['cache_lifetime'] * 60))
  121. $this -> cache($file);
  122. }
  123. /**
  124. * 对模板文件进行缓存
  125. *
  126. * @param string $file 模板文件名称
  127. * @return void
  128. */
  129. public function cache($file) {
  130. $tplfile = $this -> _getTplFile($file);
  131. if (!is_readable($tplfile)) {
  132. $this -> _throwException("模板文件 "$tplfile" 未找到或者无法打开");
  133. }
  134. // 取得模板内容
  135. $template = file_get_contents($tplfile);
  136. // 过滤
  137. $template = preg_replace("//s", "{\1}", $template);
  138. // 替换语言包变量
  139. // $template = preg_replace("/{langs+(.+?)}/ies", "languagevar('\1')", $template);
  140. // 替换 PHP 换行符
  141. $template = str_replace("{LF}", "="\n"?>", $template);
  142. // 替换直接变量输出
  143. $varRegexp = "((\$[a-zA-Z_-][a-zA-Z0-9_-]*)"
  144. . "([[a-zA-Z0-9_-."'[]$-]+])*)";
  145. $template = preg_replace("/{(\$[a-zA-Z0-9_[]'"$.-]+)}/s", "=\1?>", $template);
  146. $template = preg_replace("/$varRegexp/es", "addquote('=\1?>')", $template);
  147. $template = preg_replace("/\?>/es", "addquote('=\1?>')", $template);
  148. // 替换模板载入命令
  149. $template = preg_replace("/[ ]*{templates+([a-z0-9_]+)}[ ]*/is",
  150. " include($template->getfile('\1')); ?> ",
  151. $template
  152. );
  153. $template = preg_replace("/[ ]*{templates+(.+?)}[ ]*/is",
  154. " include($template->getfile(\1)); ?> ",
  155. $template
  156. );
  157. // 替换特定函数
  158. $template = preg_replace("/[ ]*{evals+(.+?)}[ ]*/ies",
  159. "stripvtags(' \1 ?>','')",
  160. $template
  161. );
  162. $template = preg_replace("/[ ]*{echos+(.+?)}[ ]*/ies",
  163. "stripvtags(' echo \1; ?>','')",
  164. $template
  165. );
  166. $template = preg_replace("/([ ]*){elseifs+(.+?)}([ ]*)/ies",
  167. "stripvtags('\1 } elseif(\2) { ?>\3','')",
  168. $template
  169. );
  170. $template = preg_replace("/([ ]*){else}([ ]*)/is",
  171. "\1 } else { ?>\2",
  172. $template
  173. );
  174. // 替换循环函数及条件判断语句
  175. $nest = 5;
  176. for ($i = 0; $i
  177. $template = preg_replace("/[ ]*{loops+(S+)s+(S+)}[ ]*(.+?)[ ]*{/loop}[ ]*/ies",
  178. "stripvtags(' if(is_array(\1)) { foreach(\1 as \2) { ?>','\3 } } ?>')",
  179. $template
  180. );
  181. $template = preg_replace("/[ ]*{loops+(S+)s+(S+)s+(S+)}[ ]*(.+?)[ ]*{/loop}[ ]*/ies",
  182. "stripvtags(' if(is_array(\1)) { foreach(\1 as \2 => \3) { ?>','\4 } } ?>')",
  183. $template
  184. );
  185. $template = preg_replace("/([ ]*){ifs+(.+?)}([ ]*)(.+?)([ ]*){/if}([ ]*)/ies",
  186. "stripvtags('\1 if(\2) { ?>\3','\4\5 } ?>\6')",
  187. $template
  188. );
  189. }
  190. // 常量替换
  191. $template = preg_replace("/{([a-zA-Z_-][a-zA-Z0-9_-]*)}/s",
  192. "=\1?>",
  193. $template
  194. );
  195. // 删除 PHP 代码断间多余的空格及换行
  196. $template = preg_replace("/ ?>[ ]*
  197. // 其他替换
  198. $template = preg_replace("/"(http)?[w./:]+?[^"]+?&[^"]+?"/e",
  199. "transamp('\0')",
  200. $template
  201. );
  202. $template = preg_replace("/<script>]*?src="(.+?)".*?>s*</script>/ise",</script>
  203. "stripscriptamp('\1')",
  204. $template
  205. );
  206. $template = preg_replace("/[ ]*{blocks+([a-zA-Z0-9_]+)}(.+?){/block}/ies",
  207. "stripblock('\1', '\2')",
  208. $template
  209. );
  210. // 添加 md5 及过期校验
  211. $md5data = md5_file($tplfile);
  212. $expireTime = time();
  213. $template = " if (!class_exists('template')) die('Access Denied');"
  214. . "$template->getInstance()->check('$file', '$md5data', $expireTime);"
  215. . "?> $template";
  216. // 写入缓存文件
  217. $cachefile = $this -> _getCacheFile($file);
  218. $makepath = $this -> _makepath($cachefile);
  219. if ($makepath !== true)
  220. $this -> _throwException("无法创建缓存目录 "$makepath"");
  221. file_put_contents($cachefile, $template);
  222. }
  223. /**
  224. * 将路径修正为适合操作系统的形式
  225. *
  226. * @param string $path 路径名称
  227. * @return string
  228. */
  229. protected function _trimpath($path) {
  230. return str_replace(array('/', '\', '//', '\\'), self :: DIR_SEP, $path);
  231. }
  232. /**
  233. * 获取模板文件名及路径
  234. *
  235. * @param string $file 模板文件名称
  236. * @return string
  237. */
  238. protected function _getTplFile($file) {
  239. return $this -> _trimpath($this -> _options['template_dir'] . self :: DIR_SEP . $file);
  240. }
  241. /**
  242. * 获取模板缓存文件名及路径
  243. *
  244. * @param string $file 模板文件名称
  245. * @return string
  246. */
  247. protected function _getCacheFile($file) {
  248. $file = preg_replace('/.[a-z0-9-_]+$/i', '.cache.php', $file);
  249. return $this -> _trimpath($this -> _options['cache_dir'] . self :: DIR_SEP . $file);
  250. }
  251. /**
  252. * 根据指定的路径创建不存在的文件夹
  253. *
  254. * @param string $path 路径/文件夹名称
  255. * @return string
  256. */
  257. protected function _makepath($path) {
  258. $dirs = explode(self :: DIR_SEP, dirname($this -> _trimpath($path)));
  259. $tmp = '';
  260. foreach ($dirs as $dir) {
  261. $tmp .= $dir . self :: DIR_SEP;
  262. if (!file_exists($tmp) && !@mkdir($tmp, 0777))
  263. return $tmp;
  264. }
  265. return true;
  266. }
  267. /**
  268. * 抛出一个错误信息
  269. *
  270. * @param string $message
  271. * @return void
  272. */
  273. protected function _throwException($message) {
  274. throw new Exception($message);
  275. }
  276. }
  277. ?>
复制代码
  1. 模板函数文件
  2. /**
  3. * 模板替换中需要用到的函数
  4. * http://blog.qita.in
  5. */
  6. function transamp($template) {
  7. $template = str_replace('&', '&', $template);
  8. $template = str_replace('&', '&', $template);
  9. $template = str_replace('"', '"', $template);
  10. return $template;
  11. }
  12. function stripvtags($expr, $statement) {
  13. $expr = str_replace("\"", """, preg_replace("//s", "\1", $expr));
  14. $statement = str_replace("\"", """, $statement);
  15. return $expr . $statement;
  16. }
  17. function addquote($var) {
  18. return str_replace("\"", """, preg_replace("/[([a-zA-Z0-9_-.-]+)]/s", "['\1']", $var));
  19. }
  20. function stripscriptamp($s) {
  21. $s = str_replace('&', '&', $s);
  22. return "<script src="%5C%22%24s%5C%22" type='"text/javascript"'></script>";
  23. }
  24. function stripblock($var, $s) {
  25. $s = str_replace('\"', '"', $s);
  26. $s = preg_replace("//", "{$\1}", $s);
  27. preg_match_all("//e", $s, $constary);
  28. $constadd = '';
  29. $constary[1] = array_unique($constary[1]);
  30. foreach($constary[1] as $const) {
  31. $constadd .= '$__' . $const .' = ' . $const . ';';
  32. }
  33. $s = preg_replace("//", "{$__\1}", $s);
  34. $s = str_replace('?>', " $$var .=
  35. $s = str_replace('', " EOF; ", $s);
  36. return " $constadd$$var = ";
  37. }
  38. ?>
复制代码


热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法

本专题系统整理pixiv网页版官网入口及登录访问方式,涵盖官网登录页面直达路径、在线阅读入口及快速进入方法说明,帮助用户高效找到pixiv官方网站,实现便捷、安全的网页端浏览与账号登录体验。

797

2026.02.13

微博网页版主页入口与登录指南_官方网页端快速访问方法
微博网页版主页入口与登录指南_官方网页端快速访问方法

本专题系统整理微博网页版官方入口及网页端登录方式,涵盖首页直达地址、账号登录流程与常见访问问题说明,帮助用户快速找到微博官网主页,实现便捷、安全的网页端登录与内容浏览体验。

272

2026.02.13

Flutter跨平台开发与状态管理实战
Flutter跨平台开发与状态管理实战

本专题围绕Flutter框架展开,系统讲解跨平台UI构建原理与状态管理方案。内容涵盖Widget生命周期、路由管理、Provider与Bloc状态管理模式、网络请求封装及性能优化技巧。通过实战项目演示,帮助开发者构建流畅、可维护的跨平台移动应用。

144

2026.02.13

TypeScript工程化开发与Vite构建优化实践
TypeScript工程化开发与Vite构建优化实践

本专题面向前端开发者,深入讲解 TypeScript 类型系统与大型项目结构设计方法,并结合 Vite 构建工具优化前端工程化流程。内容包括模块化设计、类型声明管理、代码分割、热更新原理以及构建性能调优。通过完整项目示例,帮助开发者提升代码可维护性与开发效率。

25

2026.02.13

Redis高可用架构与分布式缓存实战
Redis高可用架构与分布式缓存实战

本专题围绕 Redis 在高并发系统中的应用展开,系统讲解主从复制、哨兵机制、Cluster 集群模式及数据分片原理。内容涵盖缓存穿透与雪崩解决方案、分布式锁实现、热点数据优化及持久化策略。通过真实业务场景演示,帮助开发者构建高可用、可扩展的分布式缓存系统。

92

2026.02.13

c语言 数据类型
c语言 数据类型

本专题整合了c语言数据类型相关内容,阅读专题下面的文章了解更多详细内容。

53

2026.02.12

雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法
雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法

本专题系统整理雨课堂网页版官方入口及在线登录方式,涵盖账号登录流程、官方直连入口及平台访问方法说明,帮助师生用户快速进入雨课堂在线教学平台,实现便捷、高效的课程学习与教学管理体验。

15

2026.02.12

豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法
豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法

本专题汇总豆包AI官方网页版入口及在线使用方式,涵盖智能写作工具、图片生成体验入口和官网登录方法,帮助用户快速直达豆包AI平台,高效完成文本创作与AI生图任务,实现便捷智能创作体验。

717

2026.02.12

PostgreSQL性能优化与索引调优实战
PostgreSQL性能优化与索引调优实战

本专题面向后端开发与数据库工程师,深入讲解 PostgreSQL 查询优化原理与索引机制。内容包括执行计划分析、常见索引类型对比、慢查询优化策略、事务隔离级别以及高并发场景下的性能调优技巧。通过实战案例解析,帮助开发者提升数据库响应速度与系统稳定性。

64

2026.02.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Python Web框架Flask进阶视频教程
Python Web框架Flask进阶视频教程

共12课时 | 2.9万人学习

Python Web框架Flask入门视频教程
Python Web框架Flask入门视频教程

共7课时 | 2.6万人学习

后盾网smaryt模板引擎视频教程
后盾网smaryt模板引擎视频教程

共14课时 | 2.7万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号