Advertisement
Guest User

HTPL

a guest
Jan 26th, 2015
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.71 KB | None | 0 0
  1. <?php
  2.  
  3. $tpl = new Tpl();
  4. $tpl->addVar("test", "HelloWorld");
  5. $tpl->display("test.tpl");
  6.  
  7. /*
  8. test.tpl:
  9. <html>
  10. <head>
  11.     <title>Hello World!</title>
  12. </head>
  13. <body>
  14.     {test}
  15. </body>
  16. </html>
  17. */
  18.  
  19. class Tpl {
  20.  
  21.     private $vars = array();
  22.  
  23.     private $templateDir = "./";
  24.     private $templateExt = ".tpl";
  25.  
  26.     public function addVar($varName, $varValue){
  27.         $this->vars[$varName] = $varValue;
  28.     }
  29.  
  30.     public function display($file){
  31.         $file = $this->templateDir.$file.$this->templateExt; // Создание полного пути к файлу
  32.        
  33.         if(!file_exists($file)) throw new TplException("File: ".$file." not found"); // Проверка файла на наличие
  34.        
  35.         $text = file_get_contents($file); // Получаем текст из файла
  36.  
  37.         foreach ($this->vars as $key => $value) {            // Замена
  38.             $text = str_replace('{'.$key.'}', $value, $text);  // Переменных
  39.         }                              // В шаблоне
  40.  
  41.         preg_match_all('/\<\?php(.+?)\?\>/is', $text, $phpCode); // Парсинг PHP кода
  42.        
  43.         $this->evalArray($phpCode[1]); // Выполнение PHP кода
  44.        
  45.         echo $text; // Вывод результата на экран
  46.     }
  47.  
  48.     public function setTemplateExtension($ext){
  49.         $this->templateExt = ".".$ext;
  50.     }
  51.  
  52.     public function setTemplateDir($dir){
  53.         if(!is_dir($dir)) throw new TplException("$dir is not dir");
  54.         $this->templateDir = $dir;
  55.     }
  56.  
  57.     private function evalArray($arr){
  58.         if(!is_array($arr)) throw new TplException("$arr is not array");
  59.         foreach($arr as $php){
  60.             if(is_array($php)){  $this->evalArray($php); continue; }
  61.             eval($php);
  62.         }
  63.     }
  64. }
  65.  
  66. class TplException extends Exception { function __construct($msg){ $this->message = $msg; } }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement