Advertisement
Guest User

templater.php

a guest
Jul 23rd, 2014
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.95 KB | None | 0 0
  1. <?php
  2.     mb_internal_encoding('utf-8');
  3.  
  4.     class Templater {
  5.         private $vars = array(); //Список заменяемых в шаблоне переменных
  6.  
  7.  
  8.         public function render($view_name) { //Вывести на экран шаблон
  9.             $view_file = fopen("views/{$view_name}.php", 'r');
  10.             $view = fread($view_file, filesize("views/{$view_name}.php"));
  11.             fclose($view_file);
  12.  
  13.             $view = $this->replace($this->vars, $view);
  14.  
  15.             echo $view;
  16.         }
  17.  
  18.  
  19.         public function addVar($name, $value) { //Добавить переменную в массив заменяемых в шаблоне переменных
  20.             $this->vars[$name] = $value;
  21.         }
  22.  
  23.  
  24.         private function replace($vars, $view) { //Заменяем в шаблоне штуки в {}
  25.             $this->replaceVars($vars, $view);
  26.             $this->replaceLinks($vars, $view);
  27.  
  28.             return $view;
  29.         }
  30.  
  31.  
  32.         private function replaceVars(&$vars, &$view) { //Заменяем переменные
  33.             $vars = array_map(function ($var) { return htmlspecialchars($var, ENT_QUOTES); },
  34.                               $vars);
  35.  
  36.             foreach ($vars as $name => $value) {
  37.                 $view = preg_replace('/[{][ ]*'.preg_quote($name).'[ ]*[}]/ui', $value, $view);
  38.             }
  39.         }
  40.  
  41.  
  42.         private function replaceLinks(&$vars, &$view) { //Заменяем ссылки
  43.             $linkTemplate = '/[{][ ]*link[(][ ]*[\'"](.+)[\'"],[ ]*[\'"](.+)[\'"][ ]*[)][ ]*[}]/ui';
  44.             //$view = preg_replace($linkTemplate, '<a href="$2">'.htmlspecialchars("$1", ENT_QUOTES).'</a>', $view);
  45.             $view = preg_replace_callback($linkTemplate,
  46.                                           function ($m) { return '<a href="'.$m[2].'">'.htmlspecialchars($m[1], ENT_QUOTES).'</a>'; },
  47.                                           $view);
  48.         }
  49.     }
  50. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement