欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP最简单的模板引擎之一

程序员文章站 2024-02-05 09:57:34
...
自用模板引擎。
  1. define('APP_PATH', __DIR__);
  2. class Template{
  3. private static $_vars;
  4. private static $_path;
  5. private static $_prefix;
  6. private function __construct() {}
  7. public static function init($path = null) {
  8. if(isset($path)&&($path!='')) self::$_path=APP_PATH.'/templates/'.$path.'/';
  9. else self::$_path = APP_PATH.'/templates/';
  10. self::$_vars = array();
  11. }
  12. public static function set_path($path) {
  13. self::$_path = $path;
  14. }
  15. public static function set_prefix($prefix) {
  16. self::$_prefix = $prefix;
  17. }
  18. public static function assign($key, $value = null)
  19. { if(!isset(self::$_vars)) self::init();
  20. if (is_array($key)) self::$_vars = array_merge(self::$_vars,$key);
  21. elseif (($key != '')&&(isset($value)))
  22. self::$_vars[$key] = $value;
  23. }
  24. public static function fetch($file) {
  25. if(!isset(self::$_vars)) self::init();
  26. if(count(self::$_vars)>0)
  27. { extract(self::$_vars,EXTR_PREFIX_ALL,self::$_prefix);
  28. self::$_vars = array();
  29. }
  30. ob_start();
  31. include self::$_path . $file ;
  32. $contents = ob_get_contents();
  33. ob_end_clean();
  34. self::$_path = null;
  35. return preg_replace('!\s+!', ' ', $contents);
  36. }
  37. }
  38. ?>
复制代码