Home > Backend Development > PHP Tutorial > Discuz template engine

Discuz template engine

WBOY
Release: 2016-07-25 09:06:18
Original
1387 people have browsed it
Discuz template engine

Discuz’s template engine is a relatively good template engine class. I found it on the Internet a long time ago. Visually, this Discuz’s template engine should be very old. It is a version before DZ7.2. I also use it very smoothly. Share it. Download this template class.

There are two files. A template class, a function that needs to be used in template replacement
Original address: http://blog.qita.in

  1. ?/**
  2. * Template class - parsed using Discuz template engine
  3. * http://blog.qita.in
  4. */
  5. require_once (DIR_ROOT . '/../function/template.func.php');
  6. class Template {
  7. const DIR_SEP = DIRECTORY_SEPARATOR;
  8. /**
  9. * Template instance
  10. *
  11. * @staticvar
  12. * @var object Template
  13. */
  14. protected static $_instance;
  15. /**
  16. * Template parameter information
  17. *
  18. * @var array
  19. */
  20. protected $_options = array();
  21. /**
  22. * Singleton mode calling method
  23. *
  24. * @static
  25. * @return object Template
  26. */
  27. public static function getInstance( ) {
  28. if (!self :: $_instance instanceof self)
  29. self :: $_instance = new self();
  30. return self :: $_instance;
  31. }
  32. /**
  33. * Constructor
  34. *
  35. * @return void
  36. */
  37. private function __construct () {
  38. $this -> _options = array('template_dir' => 'templates' . self :: DIR_SEP, // The directory where the template file is located
  39. 'cache_dir' => 'templates' . self :: DIR_SEP . 'cache' . self :: DIR_SEP, // Directory where cache files are stored
  40. 'auto_update' => false, // Whether to regenerate the cache when the template file is changed
  41. 'cache_lifetime' => 0, // Cache life cycle ( minutes), 0 means permanent
  42. );
  43. }
  44. /**
  45. * Set template parameter information
  46. *
  47. * @param array $options parameter array
  48. * @return void
  49. */
  50. public function setOptions(array $options) {
  51. foreach ($options as $name => $value)
  52. $this - > set($name, $value);
  53. }
  54. /**
  55. * Set template parameters
  56. *
  57. * @param string $name parameter name
  58. * @param mixed $value parameter value
  59. * @return void
  60. */
  61. public function set($name, $value) {
  62. switch ($name) {
  63. case 'template_dir':
  64. $ value = $this -> _trimpath($value);
  65. if (!file_exists($value))
  66. $this -> _throwException("The specified template directory "$value"" was not found);
  67. $this -> ; _options['template_dir'] = $value;
  68. break;
  69. case 'cache_dir':
  70. $value = $this -> _trimpath($value);
  71. if (!file_exists($value))
  72. $this -> ; _throwException("The specified cache directory "$value"" was not found);
  73. $this -> _options['cache_dir'] = $value;
  74. break;
  75. case 'auto_update':
  76. $this -> _options[ 'auto_update'] = (boolean) $value;
  77. break;
  78. case 'cache_lifetime':
  79. $this -> _options['cache_lifetime'] = (float) $value;
  80. break;
  81. default:
  82. $this -> ; _throwException("Unknown template configuration option "$name"");
  83. }
  84. }
  85. /**
  86. * Set template parameters through magic method
  87. *
  88. * @see Template::set()
  89. * @param string $name parameter name
  90. * @param mixed $value parameter value
  91. * @return void
  92. */
  93. public function __set($name, $value) {
  94. $this -> set( $name, $value);
  95. }
  96. /**
  97. * Get template file
  98. *
  99. * @param string $file template file name
  100. * @return string
  101. */
  102. public function getfile($file) {
  103. $cachefile = $this -> _getCacheFile($file);
  104. if (!file_exists($ cachefile))
  105. $this -> cache($file);
  106. return $cachefile;
  107. }
  108. /**
  109. * Check whether the template file needs to update the cache
  110. *
  111. * @param string $file template file name
  112. * @param string $md5data template file md5 verification information
  113. * @param integer $md5data template file expiration time verification information
  114. * @return void
  115. */
  116. public function check($file, $md5data, $expireTime) {
  117. if ( $this -> _options['auto_update'] && md5_file($this -> _getTplFile($file)) != $md5data)
  118. $this -> cache($file);
  119. if ($this -> _options['cache_lifetime'] != 0 && (time() - $expireTime >= $this -> _options['cache_lifetime'] * 60))
  120. $this -> cache($file);
  121. }
  122. /**
  123. * Cache template files
  124. *
  125. * @param string $file template file name
  126. * @return void
  127. */
  128. public function cache($file) {
  129. $tplfile = $this -> _getTplFile($file);
  130. if (!is_readable($tplfile)) {
  131. $this -> ; _throwException("Template file "$tplfile" was not found or could not be opened");
  132. }
  133. // Get template content
  134. $template = file_get_contents($tplfile);
  135. // Filter/s", "{\1}", $template);
  136. // Replace language pack variables
  137. // $template = preg_replace("/{langs+(.+?)}/ies", "languagevar('\1')", $template);
  138. // Replace PHP newline character
  139. $template = str_replace("{LF}", "="\n"?>", $template);
  140. // Replace direct variable output
  141. $varRegexp = "((\$[a-zA-Z_x7f-xff][a-zA- Z0-9_x7f-xff]*)"
  142. . "([[a-zA-Z0-9_-."'[]$x7f-xff]+])*)";
  143. $template = preg_replace("/{( \$[a-zA-Z0-9_[]'"$.x7f-xff]+)}/s", "=\1?>", $template);
  144. $template = preg_replace(" /$varRegexp/es", "addquote('=\1?>')", $template);
  145. $template = preg_replace("/==$varRegexp?>? >/es", "addquote('=\1?>')", $template);
  146. // Replace template loading command
  147. $template = preg_replace("/[nrt]*{templates+( [a-z0-9_]+)}[nrt]*/is",
  148. "rn include($template->getfile('\1')); ?>rn",
  149. $template
  150. ) ;
  151. $template = preg_replace("/[nrt]*{templates+(.+?)}[nrt]*/is",
  152. "rn include($template->getfile(\1)); ?> ;rn",
  153. $template
  154. );
  155. // Replace specific function
  156. $template = preg_replace("/[nrt]*{evals+(.+?)}[nrt]*/ies",
  157. "stripvtags('< ;? \1 ?>','')",
  158. $template
  159. );
  160. $template = preg_replace("/[nrt]*{echos+(.+?)}[nrt]*/ies",
  161. " stripvtags(' echo \1; ?>','')",
  162. $template
  163. );
  164. $template = preg_replace("/([nrt]*){elseifs+(.+?)}([ nrt]*)/ies",
  165. "stripvtags('\1 } elseif(\2) { ?>\3','')",
  166. $template
  167. );
  168. $template = preg_replace("/ ([nrt]*){else}([nrt]*)/is",
  169. "\1 } else { ?>\2",
  170. $template
  171. );
  172. // Replace loop function and conditional judgment Statement
  173. $nest = 5;
  174. for ($i = 0; $i $template = preg_replace("/[nrt]*{loops+(S+)s+(S+)}[nr ]*(.+?)[nr]*{/loop}[nrt]*/ies",
  175. "stripvtags(' if(is_array(\1)) { foreach(\1 as \2) { ? >','\3 } } ?>')",
  176. $template
  177. );
  178. $template = preg_replace("/[nrt]*{loops+(S+)s+(S+)s+(S+)} [nrt]*(.+?)[nrt]*{/loop}[nrt]*/ies",
  179. "stripvtags(' if(is_array(\1)) { foreach(\1 as \2 = > \3) { ?>','\4 } } ?>')",
  180. $template
  181. );
  182. $template = preg_replace("/([nrt]*){ifs+(.+ ?)}([nr]*)(.+?)([nr]*){/if}([nrt]*)/ies",
  183. "stripvtags('\1 if(\2) { ? >\3','\4\5 } ?>\6')",
  184. $template
  185. );
  186. }
  187. // Constant replacement
  188. $template = preg_replace("/{([a-zA -Z_x7f-xff][a-zA-Z0-9_x7f-xff]*)}/s",
  189. "=\1?>",
  190. $template
  191. );
  192. // Delete PHP code break Extra spaces and line breaks
  193. $template = preg_replace("/ ?>[nr]* /s", " ", $template);
  194. // Other replacements
  195. $template = preg_replace("/"(http )?[w./:]+?[^"]+?&[^"]+?"/e",
  196. "transamp('\0')",
  197. $template
  198. );
  199. $template = preg_replace ("/<script>]*?src="(.+?)".*?>s*</script>/ise",
  200. "stripscriptamp('\1')",
  201. $template
  202. );
  203. $template = preg_replace("/[nrt]*{blocks+([a-zA-Z0-9_]+)}(.+?){/block}/ies",
  204. "stripblock(' \1', '\2')",
  205. $template
  206. );
  207. // Add md5 and expiration check
  208. $md5data = md5_file($tplfile);
  209. $expireTime = time();
  210. $template = "< ;? if (!class_exists('template')) die('Access Denied');"
  211. . "$template->getInstance()->check('$file', '$md5data', $expireTime) ;"
  212. . "?>rn$template";
  213. // Write cache file
  214. $cachefile = $this -> _getCacheFile($file);
  215. $makepath = $this -> _makepath($cachefile);
  216. if ($makepath !== true)
  217. $this -> _throwException("Unable to create cache directory "$makepath"");
  218. file_put_contents($cachefile, $template);
  219. }
  220. /**
  221. * Correct the path to a form suitable for the operating system
  222. *
  223. * @param string $path path name
  224. * @return string
  225. */
  226. protected function _trimpath($path) {
  227. return str_replace(array('/', '\', '//', '\\'), self :: DIR_SEP, $path);
  228. }
  229. / **
  230. * Get the template file name and path
  231. *
  232. * @param string $file template file name
  233. * @return string
  234. */
  235. protected function _getTplFile($file) {
  236. return $this -> _trimpath($this -> _options['template_dir'] . self :: DIR_SEP . $file);
  237. }
  238. /**
  239. * Get the template cache file name and path
  240. *
  241. * @param string $file template file name
  242. * @return string
  243. */
  244. protected function _getCacheFile($file) {
  245. $file = preg_replace('/.[a-z0-9-_]+$/i', '.cache.php', $file);
  246. return $this -> _trimpath($this -> _options['cache_dir'] . self :: DIR_SEP . $file);
  247. }
  248. /**
  249. * Create a non-existing folder based on the specified path
  250. *
  251. * @param string $path path/folder name
  252. * @return string
  253. */
  254. protected function _makepath($path) {
  255. $dirs = explode(self :: DIR_SEP, dirname($this -> _trimpath($path)));
  256. $tmp = '';
  257. foreach ($dirs as $dir) {
  258. $tmp .= $dir . self :: DIR_SEP;
  259. if (!file_exists($tmp) && !@mkdir($tmp, 0777))
  260. return $tmp;
  261. }
  262. return true;
  263. }
  264. /**
  265. * Throw an error message
  266. *
  267. * @param string $message
  268. * @return void
  269. */
  270. protected function _throwException($message) {
  271. throw new Exception($message);
  272. }
  273. }
  274. ?>
复制代码
  1. 模板函数文件
  2. /**
  3. * Functions needed for template replacement
  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_-.x7f-xff]+)]/s", "['\1']", $var));
  19. }
  20. function stripscriptamp($s) {
  21. $s = str_replace('&', '&', $s);
  22. return "";
  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('?>', "n$$var .= $s = str_replace('', "nEOF;n", $s);
  35. return "";
  36. }
  37. ?>
复制代码


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template