Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $tpl = new Tpl();
- $tpl->addVar("test", "HelloWorld");
- $tpl->display("test.tpl");
- /*
- test.tpl:
- <html>
- <head>
- <title>Hello World!</title>
- </head>
- <body>
- {test}
- </body>
- </html>
- */
- class Tpl {
- private $vars = array();
- private $templateDir = "./";
- private $templateExt = ".tpl";
- public function addVar($varName, $varValue){
- $this->vars[$varName] = $varValue;
- }
- public function display($file){
- $file = $this->templateDir.$file.$this->templateExt; // Создание полного пути к файлу
- if(!file_exists($file)) throw new TplException("File: ".$file." not found"); // Проверка файла на наличие
- $text = file_get_contents($file); // Получаем текст из файла
- foreach ($this->vars as $key => $value) { // Замена
- $text = str_replace('{'.$key.'}', $value, $text); // Переменных
- } // В шаблоне
- preg_match_all('/\<\?php(.+?)\?\>/is', $text, $phpCode); // Парсинг PHP кода
- $this->evalArray($phpCode[1]); // Выполнение PHP кода
- echo $text; // Вывод результата на экран
- }
- public function setTemplateExtension($ext){
- $this->templateExt = ".".$ext;
- }
- public function setTemplateDir($dir){
- if(!is_dir($dir)) throw new TplException("$dir is not dir");
- $this->templateDir = $dir;
- }
- private function evalArray($arr){
- if(!is_array($arr)) throw new TplException("$arr is not array");
- foreach($arr as $php){
- if(is_array($php)){ $this->evalArray($php); continue; }
- eval($php);
- }
- }
- }
- class TplException extends Exception { function __construct($msg){ $this->message = $msg; } }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement