Вот хотел послушать гениальные идеи людей по шаблонизаторам я например написал так... например в шаблоне Code: <----START NEWS HERE----> {NEWS} <----END NEWS HERE----> а в скрипте идёт PHP: $where[0] = '<----START NEWS HERE---->'; $where[1] = '<----END NEWS HERE---->'; $what['{NEWS}'] = $news; $tpl = $templ->templ($where,$what); бла бла echo $tpl; надеюсь вы примерно поняли как это работает...=) в некоторых случьях это бывает удобно ... но всёже по мне это ужасная реализация шаблонов.. может у вас есть светлые идеи?=)
А почему ужасная? PHP: $where[0] = '<----START NEWS HERE---->'; $where[1] = '<----END NEWS HERE---->'; По мойму даже очень ужобно
Все хорошо, но зачем придумывать велосипед? Смотря под какие цели нужен шаблонизатор и что он должен уметь. Если просто заменять вариэйблы тогда пойдет...
Не удобно в том плане что если шаблон большой то пол шаблона это <---blabla start ----> <---blabla end----> <---blabla start ----> <---blabla end----> etc... и как сделать так тоб пхп код в шаблоне не исполнялся?
NOmeR1 Твой способ помойму немного не удобен т.к я например использовать цикл части шаблона например Code: <---TEMPLATE START---> тут шапка <---NEWS START---> <tr><td> {NEWS} </td</tr <---NEWS END---> фоот <---TEMPLATE END---> а в файле могу сделать так PHP: $where[0] = '<---TEMPLATE START--->'; $where[1] = '<---NEWS START--->'; $tpl = $templ->templ($where,0); $where[0] = '<---NEWS START--->'; $where[1] = '<---NEWS END--->'; запрос.. while ($news = mysql_fetch_assoc($result)) { $what['{NEWS}'] = $news['content']; $tpl .=$templ->templ($where,$what); } а тут добовляем ещё и фоот echo $tpl;
Вот такой простенький шаблонизатор юзаю я yuactpl.php PHP: <? if(!class_exists("yuactpl")) { class yuactpl { var $tpls=array(); var $ptpls=array(); //parsed templates var $wtpls=array(); //while templates (blocks, used many times) var $pwtpls=array(); //parsed while templates //** function file2string($file) { if (file_get_contents($file)) { return file_get_contents($file); } else { return false; } /* if(file_exists($file) && is_readable($file)) { $f=fopen($file,"rb"); $filecontent=fread($f,filesize($file)); fclose($f); return $filecontent; }else { return false; } */ } //** function loadtpl($tpl) { if($result=$this->file2string($tpl)) { $this->tpls[$tpl]=preg_replace_callback('/\<script language="php"\>(.*)\<\/script\>/isU',create_function('$data','return eval($data[1]);'),$result); return true; } return false; } //** function parse($rarray,$tpl) //replace array ( array('title' => 'Welcome', 'body' => 'This is an example',) ) { if(!isset($this->tpls[$tpl]) or !is_array($rarray)) return false; //** $tpltxt/*template text*/=$this->tpls[$tpl]; //** foreach($rarray as $key=>$value) { if(!is_array($value)) $tpltxt=str_replace('{'.$key.'}', $value, $tpltxt); } //** $this->ptpls[$tpl]=$tpltxt; return true; } //** function getparsedtext($tpl) { if(!isset($this->ptpls[$tpl])) return false; //** return $this->ptpls[$tpl]; } //** function loadwtpl($tpl,$delimiter="<!--delimiter-->") { if($result=$this->file2string($tpl)) { $this->wtpls[$tpl]=explode($delimiter, preg_replace_callback('/\<php\>(.*)\<\/php\>/isU',create_function('$data','return eval($data[1]);'),$result)); return true; } return false; } //** function wparse($rarray,$tpl,$n) //replace array ( array('title' => 'Welcome', 'body' => 'This is an example',) ) { if(!isset($this->wtpls[$tpl][$n]) or !is_array($rarray)) return false; //** $tpltxt/*template text*/=$this->wtpls[$tpl][$n]; //** foreach($rarray as $key=>$value) { if(!is_array($value)) $tpltxt=str_replace('{'.$key.'}', $value, $tpltxt); } //** $this->pwtpls[$tpl][$n]=$tpltxt; return true; } //** function wparseall($rarray,$tpl) { if(!isset($this->wtpls[$tpl]) or !is_array($rarray)) return false; //** foreach($rarray as $key=>$value) { $this->wtpls[$tpl]=str_replace('{'.$key.'}', $value, $this->wtpls[$tpl]); } //** return true; } //** function getwparsedtext($tpl,$n) { if(!isset($this->pwtpls[$tpl][$n])) return false; //** return $this->pwtpls[$tpl][$n]; } //** function fastparse($tpl,$rarray=array(),$echo=true) { if(!isset($this->tpls[$tpl])) $this->loadtpl($tpl); $this->parse($rarray,$tpl); if($echo) echo $this->getparsedtext($tpl); else return $this->getparsedtext($tpl); } //** function fastwparse($tpl,$rarray=array(),$num=0,$echo=true) { if(!isset($this->wtpls[$tpl])) $this->loadwtpl($tpl); $this->wparse($rarray,$tpl,$num); if($echo) echo $this->getwparsedtext($tpl,$num); else return $this->getwparsedtext($tpl,$num); } } } ?> index.php PHP: <?php include('yuactpl.php'); $title = "blabla" // допустим выбирается с БД $content = "привет. я задрот...." // тоже с БД $tp = new yuactpl; $template = "./index.tpl"; $page_data = array( 'title' => $title, 'content' => $content ); $tp->fastwparse($template, $page_data); ?> index.tpl HTML: <html> <head><title>{title}</title> <meta http-equiv="content-type" content="text/html; charset=utf8"/> </head> <body> {content} </body> </html> Быстрый и удобный PS Ещё есть возможность использовать в шаблоне php код: в тегах пишется HTML: <script language="php">echo "bla"</script> Если интересно, почитайте http://forum.dklab.ru/viewtopic.php?p=38883
Вот - если кому интересно, сделал скрипт по этой теме, что-то вроде "системы" {if выражение}утверждение{/if} Вот к примеру у нас есть массивы Code: $true = array(true, false, true, false); $false = array(false, true, false, true); И файл с шаблоном Code: 1 {if $true[0] == false}2{/if} {if $true[1] == $false[0]}3 {if false == $true[2]}8{/if} 5{/if} {if false === $false[0]} {if $true[0] == $false[0]}6{/if} 7 {if $true[1] == $false[3]} 8 {/if} {/if} 9 Ну и сам скрипт Code: <?php function format_eval($matches) { $exp = preg_replace('~\$((?![0-9])[a-zA-Z0-9_\x7F-\xFF]+)~', '$GLOBALS[\'\\1\']', $matches[1]); $txt = var_export($matches[2], true); eval('$string = ('.$exp.') ? '.$txt.' : NULL;'); return $string; } $text = file_get_content('template.html'); // template.html - файл с шаблоном $pattern = '~{if (.+)}(((?>(?R)|(((?!{if .+})|{/if})).+)+)+){/if}~isU'; while(preg_match_all($pattern, $text, $matches)) { $text = preg_replace_callback($pattern, 'format_eval', $text); } echo $text; ?> Вывод: Code: 1 3 5 7 9
Если честно, я не понимаю зачем вообще нужны такие шаблонизаторы, ведь это пхп с другим синтаксисом. Впринципе если не собираешься выпускать какой-нибудь движок - лучше забить на них.
Практически во всех проектах использую Не такой уж smarty и "тяжелый", но добавляет много гибкости, мне нравиться... + 2 уровня кэширования(встроено) Не ну понятно, если у тебя просто там какой-то новостник или пару страничек, то не стоит использовать... а в php еще довольно популярный шаблонизатор FastTemplate(уже не помню как пишеться)... но в простых проэктах использую самописный, всего на пару функций а smarty очень даже ниче, только ихня вставка [ php ] [ /php ] - зло Все сводиться к вечной теме - разделения логики и представления
Хватит придумывать велосипед. Я для сабжа использовал три варианта шаблонизатора: 1) PHP. Ибо разрабатывался как шаблонизатор. <?=$var?> 2) Smarty 3) XSLT
Поэтому пользуюсь своим или smarty(система кэширования радует) XSLT - никогда не использовал, только слегка читал Стоит ли использовать? или проще 2 первыми вариантами обойтись? ведь вроде нормально работает