+ -
当前位置:首页 → 问答吧 → 加上注释也只有156行的仿TP模板类, 浓缩就是精华!

加上注释也只有156行的仿TP模板类, 浓缩就是精华!

时间:2010-01-13

来源:互联网

使用方法很简单 include template('模板文件名'); 就可以了, 模板文件名不带后缀的哦!
演示
复制代码
  1. index.php
  2. include 'Template.class.php';
  3. $name = 'xiaokai';
  4. $arr       = array('one', 'two');
  5. include template('index'); //index指向模板文件/Templates/index.html

下面是模板文件
复制代码
  1. index.html
  2. {if $name == 'xiaokai'}
  3.     Hello:{$name}
  4.     {loop $arr $key $val}  //还支持{loop $arr $val}格式
  5.         {$key}--->{$val}
  6.     {/loop}
  7. {else}
  8.     {@time|date="Y-m-d", ###}  //这个是输出当前时间
  9. {/if}


模板类
复制代码
  1. <?php
  2. /**
  3. * 文件描述  模板解析类
  4. * =================================================================
  5. * 文件名称  Template.class.php
  6. * -----------------------------------------------------------------
  7. * 作    者  xiaokai<[email protected]>
  8. * -----------------------------------------------------------------
  9. * 创建时间  2010-1-6 2:11:55
  10. * =================================================================
  11. */
  12. /**
  13. * 返回模板文件完整目录
  14. *
  15. * @access  public
  16. * @param   string  $tpl    模板文件名称, 不带后缀
  17. * @return
  18. */
  19. function template($tpl = 'index')
  20. {
  21.     $tplFile    = "./Templates/{$tpl}.html";
  22.     $cacheFile  = "./Templates/Cache/{$tpl}.html.php";
  23.     !is_file($tplFile) && exit("模板文件[{$tpl}]不存在");
  24.     //修改模板文件时, 更改缓存文件
  25.     if (filemtime($tplFile) > @filemtime($cacheFile)) {
  26.         $template = new Template();
  27.         $template->cache($tplFile, $cacheFile);
  28.     }
  29.     return $cacheFile;
  30. }
  31. class Template
  32. {
  33.     /**
  34.      *  缓存模板
  35.      *
  36.      * @access  public
  37.      * @param   string  $tplFile    模板文件
  38.      * @param   string  $cacheFile  缓存文件
  39.      * @return  void
  40.      */
  41.     public function cache($tplFile, $cacheFile)
  42.     {
  43.         //缓存目录不存在则创建
  44.         if (!is_dir(dirname($cacheFile))) {
  45.             if (!@mkdir(dirnaem($cacheFile))) {
  46.                 exit('无法创建缓存目录, 请手动创建');
  47.             }
  48.         }
  49.         $data = file_get_contents($tplFile);
  50.         $data = preg_replace('/(\{)(\S.+?)(\})/ies', "\$this->compile('\\2')", $data);
  51.         return  file_put_contents($cacheFile, $data);
  52.     }
  53.     /**
  54.      * 编译模板
  55.      *
  56.      * @access  public
  57.      * @param   string  模板定界符内的字符串
  58.      * @return  string  编译后的字符串
  59.      */
  60.     protected function compile($str)
  61.     {
  62.         static $_parses = array();
  63.         $str  = trim(stripslashes($str));
  64.         //还原非模板标签 例如{124}
  65.         if (preg_match('/^[\s|\d]/is', $str)) {
  66.             return '{' . $var . '}';
  67.         }
  68.         if (isset($_parses[$str])) {
  69.             return $_parses[$str];
  70.         }
  71.         $flag = substr($str, 0, 1);
  72.         $var  = substr($str, 1);
  73.         //{$a} {$a|time="Y-m-d H:i:s"}  一般变量输出
  74.         if ($flag == '
  75. ) {
  76.             $arr = explode('|', $var);
  77.             $var = array_shift($arr);
  78.             $code = "\${$var}"; //$var变量名称, 比如 a  那么code就是$a
  79.             $len = count($arr); //统计函数个数
  80.             for ($i = 0; $i < $len; $i++) {
  81.                 $args    = explode('=', $arr[$i]);  //date="Y-m-d",### 将函数名和参数分割出来
  82.                 $args[0] = trim($args[0]);  //清空函数名旁的空白
  83.                 if (isset($args[1])) {  //如果存在参数
  84.                     if (strstr($args[1], '###')) {
  85.                         $args[1] = str_replace('###', $code, $args[1]);  //将### 换为输出变量自己
  86.                         $code = "{$args[0]}({$args[1]})";
  87.                     } else {
  88.                         $code = "{$args[0]}({$code},{$args[1]})";
  89.                     }
  90.                 } else {//不存在参数, 那么自己是参数
  91.                     $code = "{$args[0]}({$code})";
  92.                 }
  93.             }
  94.             $_parses[$str] = "<?php echo ({$code}); ?>";
  95.         } else if ($flag == '#') {  //执行函数 {~include('file')}
  96.             $_parses[$str] = "<?php {$var}  ?>";
  97.         } else if ($flag == '@') { // 输出函数运行的结果
  98.             $_parses[$str] = "<?php echo ({$var}) ?>";
  99.         } else if ($flag == '~') {  //输出常量
  100.             $_parses[$str] = '<?php echo (' . strtoupper($var) . '); ?>';
  101.         } else if ($flag == '/') {  // {/*} 闭合标签
  102.             switch (strtolower($var)) {
  103.                 case 'loop' : $end = 'endforeach; endif;'; break;
  104.                 case 'if'   : $end = 'endif;'; break;
  105.                 case 'for'  : $end = 'endfor;'; break;
  106.             }
  107.             $_parses[$str] = "<?php {$end} ?>";
  108.         }
  109.         // include 标签
  110.         if (substr($str, 0, 7) == 'include') {
  111.             $file = trim(substr($str, 7));
  112.             $file = strtr($file, '.', '/');
  113.             $_parses[$str] = "<?php require_once template('{$file}'); ?>";
  114.         }
  115.         //foreach循环
  116.         if (substr($str, 0, 4) == 'loop') {
  117.             $args    = explode(' ', substr($var, 4));
  118.             $foreach = '<?php if (is_array('.$args[0].') || is_object('.$args[0].')) : foreach(' . $args[0] . ' as ' . $args['1'];
  119.             if (count($args) == 3) {
  120.                 $foreach .= ' => ' . $args[2];
  121.             }
  122.             $_parses[$str] =  $foreach . ') : ?>';
  123.         }
  124.         //if标签
  125.         if (substr($str, 0, 2) == 'if') {
  126.             $exp           = substr($var, 2);
  127.             $_parses[$str] ="<?php if ({$exp}) : ?>";
  128.         }
  129.         //elseif
  130.         if (substr($str, 0, 6) == 'elseif') {
  131.             $exp           = substr($var, 6);
  132.             $_parses[$str] = "<?php elseif ({$exp}) : ?>";
  133.         }
  134.         //else
  135.         if (substr($str, 0, 4) == 'else') {
  136.             $_parses[$str] = "<?php else : ?>";
  137.         }
  138.         //还原标签
  139.         return isset($_parses[$str]) ? $_parses[$str] : '{' . $flag . $var . '}';
  140.     }
  141. }
  142. /* 文件结束 Template.class.php */



作者: xiaokai   发布时间: 2010-01-13

没用过。。试试

作者: memory   发布时间: 2010-01-13

嘿嘿。。放屁是不需要脱掉裤子滴

作者: cain   发布时间: 2010-01-14

不如看看UCHOME的引擎。。那才叫爽。。eval、foreach、for、if有这三个标签就足够了。。。一个Template。。额。。大费周章

作者: cain   发布时间: 2010-01-16