Изобретая велосипеды: PHP шаблонизатор

13 февраля 2009

Началось все с того что мне не нравятся существующие темплейтеры типа smarty. Не прет.

Написал свой, простенький, но для повседневности хватает.

вот такой вот класс:

  1. <?php
  2. class Template {
  3.     private $template;
  4.     private $vars;
  5.     private $blocks;
  6.     private $res;
  7.     private $registry;
  8.  
  9.     function __construct($registry) {
  10.         $this->registry = $registry;
  11.     }
  12.  
  13.     private function getvars($block="")
  14.     {
  15.         $str="";
  16.         if ($block=="")
  17.         {
  18.             $str=$this->res;
  19.         }
  20.         else
  21.         {
  22.             if (isset($this->blocks[$block]))
  23.             {
  24.                 $str=$this->blocks[$block];
  25.             }
  26.         }
  27.         $m=array();
  28.         preg_match_all("/{%(.*)?%}/ismU",$str,$m,PREG_SET_ORDER);
  29.         return $this->assoc($m);
  30.     }
  31.  
  32.     private function assoc($arr)
  33.     {
  34.         $r=array();
  35.         if (count($arr)>0)
  36.         {
  37.             foreach ($arr as $v)
  38.             {
  39.                 $r[$v[1]]=$v[0];
  40.             }
  41.         }
  42.         return $r;
  43.     }
  44.  
  45.     private function getblocks()
  46.     {
  47.         $m=array();
  48.         preg_match_all("/<!--(.*)?-->.*?<!--\/\\1-->/ismU", $this->template, $m ,PREG_SET_ORDER);
  49.         $this->blocks=$this->assoc($m);
  50.     }
  51.  
  52.     private function getinclude($data)
  53.     {
  54.         $m=array();
  55.         preg_match_all("/<!--include:(.*)?-->/ismU", $this->template, $m ,PREG_SET_ORDER);
  56.         foreach ($m as $i)
  57.         {
  58.             $t=new template($this->registry);
  59.             $this->res=str_replace($i[0],$t->compile($data,site_path.$i[1]),$this->res);
  60.             unset($t);
  61.         }
  62.     }
  63.  
  64.     function getphp()
  65.     {
  66.         $m=array();
  67.         preg_match_all("/{--(.*)?--}/ismU", $this->res, $m ,PREG_SET_ORDER);
  68.         $out="";
  69.         foreach ($m as $p)
  70.         {
  71.             ob_start();
  72.             eval ("echo ".$p[1].";");
  73.             $out = ob_get_clean();
  74.             $this->res=str_replace($p[0],$out,$this->res);
  75.         }
  76.     }
  77.  
  78.     private function setvars($tpl,$vars,$d)
  79.     {
  80.         $str=$tpl;
  81.         foreach ($vars as $var => $search)
  82.         {
  83.             if (isset($d[$var]))
  84.             {
  85.                 $str=str_replace($search,$d[$var],$str);
  86.             }
  87.             else
  88.             {
  89.                 $str=str_replace($search,"",$str);
  90.             }
  91.         }
  92.         return $str;
  93.     }
  94.  
  95.     private function compileblock($block,$data)
  96.     {
  97.         $tpl=$this->blocks[$block];
  98.         $res="";
  99.         $vars = $this->getvars($block);
  100.         //print_r($vars);
  101.         foreach($data as $d)
  102.         {
  103.             $res.=$this->setvars($tpl,$vars,$d)."\n\n";
  104.         }
  105.         $this->res=str_replace($tpl,$res,$this->res);
  106.     }
  107.  
  108.     function compile($data,$tplfile)
  109.     {
  110.         $this->template=file_get_contents($tplfile);
  111.         $this->res=$this->template;
  112.         $this->getblocks();
  113.         foreach ($this->blocks as $block => &$v)
  114.         {
  115.             if (isset($data[$block]))
  116.             {
  117.                 $this->compileblock($block,$data[$block]);
  118.             }
  119.             else
  120.             {
  121.                 $this->res=str_replace($this->blocks[$block],"",$this->res);
  122.             }
  123.         }
  124.         $this->res=$this->setvars($this->res,$this->getvars(),$data);
  125.         $this->getinclude($data);
  126.         $this->getphp();
  127.  
  128.         return $this->res;
  129.     }
  130.  
  131.     function html($data,$tplfile)
  132.     {
  133.         echo $this->compile($data,site_path.$tplfile);
  134.     }
  135. }
  136. ?>

Чтобы было проще понять, вот пример шаблона:

  1. <!--include:tpl/header.tpl-->
  2. <table class="adminlist" style="width:300px;">
  3. <tr>
  4. <th class="title" width="3%"><input name="toggle" id="toggle" value="1" onclick="checkAll(1);" type="checkbox" /></th>
  5. <th class="title" width="97%">&nbsp;</th>
  6. </tr>
  7.  
  8. <!--users-->
  9. {--('1'=='{%flag%}') ? '<tr><td colspan="2">{%gname%}</td></tr>':'' --}
  10. <tr class="row0">
  11. <td><input type="checkbox" class="checkbox" name="check_{%id%}" /></td>
  12. <td><a href="/users/edit/{%id%}">{%name%}</a></td></tr>
  13. <!--/users-->
  14.  
  15. {--('write'=='{%right%}') ? '<tr><td colspan="6" style="text-align:center;"><a href="/users/create">Добавить</a></td></tr>':''--}
  16. </table>
  17.  
  18. <!--include:tpl/footer.tpl-->

Как использовать? примерно вот так:

  1. <?php
  2. $d=array();
  3. $d['users'][1]['id']=1;
  4. $d['users'][1]['name']='User 1';
  5. $d['users'][1]['game']='Group 1';
  6. $d['users'][1]['flag']=1;
  7. $d['users'][2]['id']=2;
  8. $d['users'][2]['name']='User 2';
  9. $d['users'][2]['game']='Group 1';
  10. $d['users'][2]['flag']=0;
  11. $d['users'][3]['id']=3;
  12. $d['users'][3]['name']='User 3';
  13. $d['users'][3]['game']='Group 2';
  14. $d['users'][3]['flag']=1;
  15. $d['right']='right';
  16.  
  17. $template = new Template($registry);
  18. $template->html($d,'tpl/usersform.tpl');
  19.  
  20. ?>

Поподробнее про теги шаблона:
{%name%} — переменная
<!—include:file.tpl—> — включение внешнего шаблона (количество включений ограничено только оперативной памятью 🙂
повторяющиеся блоки оформляются так
<!—blockname—>
{%name%}
<!—/blockname—>
где blockname — это массив значений в передаваемом параметре
условия задаются вот так:
{—(‘1’=='{%flag%}’) ? ‘{%var1%}’:'{%var2%}’ —}

ссылочка на файлик класса: template.phps

Опубликовал:

5 комментариев на «“Изобретая велосипеды: PHP шаблонизатор”»

  1. $registry можно убрать, в этой версии оно не используется. а так глобальная переменная в которой все 🙂

  2. Ну да, Smarty монстр, но зачем велосипед-то изобретать? Все уже изобретено до нас. Например, TemplatePower. Быстрый, простой и ничего лишнего.

  3. Иногда изобрести велосипед во-первых интереснее, во-вторых полезнее, а в-третьих оптимальнее 😉

  4. Вячеслав:

    Большое спасибо автору за интересную статью 😉

  5. Спасибо, полезная инфа!