Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- mb_internal_encoding('utf-8');
- class Templater {
- private $vars = array(); //Список заменяемых в шаблоне переменных
- public function render($view_name) { //Вывести на экран шаблон
- $view_file = fopen("views/{$view_name}.php", 'r');
- $view = fread($view_file, filesize("views/{$view_name}.php"));
- fclose($view_file);
- $view = $this->replace($this->vars, $view);
- echo $view;
- }
- public function addVar($name, $value) { //Добавить переменную в массив заменяемых в шаблоне переменных
- $this->vars[$name] = $value;
- }
- private function replace($vars, $view) { //Заменяем в шаблоне штуки в {}
- $this->replaceVars($vars, $view);
- $this->replaceLinks($vars, $view);
- return $view;
- }
- private function replaceVars(&$vars, &$view) { //Заменяем переменные
- $vars = array_map(function ($var) { return htmlspecialchars($var, ENT_QUOTES); },
- $vars);
- foreach ($vars as $name => $value) {
- $view = preg_replace('/[{][ ]*'.preg_quote($name).'[ ]*[}]/ui', $value, $view);
- }
- }
- private function replaceLinks(&$vars, &$view) { //Заменяем ссылки
- $linkTemplate = '/[{][ ]*link[(][ ]*[\'"](.+)[\'"],[ ]*[\'"](.+)[\'"][ ]*[)][ ]*[}]/ui';
- //$view = preg_replace($linkTemplate, '<a href="$2">'.htmlspecialchars("$1", ENT_QUOTES).'</a>', $view);
- $view = preg_replace_callback($linkTemplate,
- function ($m) { return '<a href="'.$m[2].'">'.htmlspecialchars($m[1], ENT_QUOTES).'</a>'; },
- $view);
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment