PHP自寫簡單模板引擎,供新手學習
今天要寫點小東西,突然想到要用模板引擎。就“隨手”寫了一個,發上來供新手學習。搞了這麼久PHP,想想也真是感慨,當年研究了幾天的東西現在一兩個小時就弄完了,當年一起完耍的女神現在已經不知所蹤了。。。咳咳,下面是代碼:
tpl_dir = $tpl_dir; if(isset($cache_dir))$this->cache_dir = $cache_dir; if(isset($tpl_ext))$this->tpl_ext = $tpl_ext; if(isset($var_left))$this->var_left = $var_left; if(isset($var_right))$this->var_right = $var_right; } function load($tplfilename) { $tplfile = $this->tpl_dir.'/'.$tplfilename.$this->tpl_ext; if(!file_exists($tplfile)) die('Template not found: '.$tplfile); return $this->cache($tplfilename, $tplfile); } //判斷模板是否緩衝,如模板檔案有更改則重新編譯 function cache($tplname, $tpl_file) { $cache_file = $this->cache_dir.'/'.md5($tplname).'.php'; if(!file_exists($cache_file) || filemtime($tpl_file)>filemtime($cache_file)) $this->compile($tpl_file, $cache_file); return $cache_file; } //編譯模板內容到PHP格式,並寫入緩衝 function compile($tpl, $cache) { $body = file_get_contents($tpl); $vl = $this->var_left; $vr = $this->var_right; $patterns = array( "#$vl\s*include:(.+?)\s*$vr#i", "#$vl\s*if\s+(.+?)\s*$vr#i", "#$vl\s*else\s*$vr#i", "#$vl\s*elseif\s+(.+?)\s*$vr#i", "#$vl\s*endif\s*$vr#i", "#$vl\s*/if\s*$vr#i", "#$vl\s*foreach\s+(.+?):(.+?)\s*$vr#i", "#$vl\s*endforeach\s*$vr#i", "#$vl\s*/foreach\s*$vr#i", "#$vl([0-9a-zA-Z_]+?)\.([0-9a-zA-Z_]+?)\.([0-9a-zA-Z_]+?)$vr#i", "#$vl([0-9a-zA-Z_]+?)\.([0-9a-zA-Z_]+?)$vr#i", "#$vl([0-9a-zA-Z_\[\]\'\"]+?)$vr#i", "#$vl([0-9a-zA-Z_]+?):(.*?)$vr#i" ); $replacements = array( "", "", "", "", "", "", "0):\$autoindex=0;foreach($\\1 as \\2):\$autoindex++; ?>", "", "", "", "", "", "" ); $body = preg_replace($patterns, $replacements, $body); file_put_contents($cache, "".$body); }}$view = new view();function show($tpl) { global $view; return $view->load($tpl);}
使用方法PHP檔案:
'rows','b'=>array('c'=>'inarray')); include show('index');
使用方法HTML模板檔案:
{title}你好,僅供參考
{a.a}{a.b.c}
{foreach a:$v}{autoindex}.{v}
{/foreach}{include:footer}
模板檔案放在template目錄,緩衝放在cahce目錄,這兩個目錄都要手動建立,緩衝加上判斷不可直接存取。可以使用
{include:子模板}
{if 條件}
{foreach 變數:as語句},$autoindex為自增變數
{調用函數:參數}
{變數},包含陣列變數簡化寫法(最多隻支援三維數組)
等文法。
好了,整個模板引擎實現比較簡單,因為一直比較喜歡這種include方式的模板,只供新手學習原理就好了。
=====================國際慣例=======================
剛開始學著寫一些部落格,寫得不好的地方請見諒,覺得還可以就賞臉贊下吧!
我的QQ群(PHP)336533596,QQ 451309839,歡迎加入。相互交流,聊天吹牛~