標籤:php 自訂 smarty 模板引擎類 高洛峰 細說php
smarty模板引擎類簡單工作原理
利用Smarty 模板引擎類對模板檔案中的變數進行編譯,編譯過程其實就是利用Regex翻譯成PHP檔案。例如 模板檔案中{$title} 利用正則運算式找到並替換成 <?php echo $this->vars[‘title‘];?>
自訂 Smarty 模板引擎類 smarty.class.php頁面
<?php/* * 自訂Smarty模板引擎類 */ class Smarty{ private $vars = array(); //第一個向模板中分配變數 //有兩個參數 一個參數是模板中的變數名,一個時分配給它的變數值 public function assign($name,$value=null){ if($name != ‘ ‘) $this->vars[$name]=$value; } //載入指定的模板 並顯示 //有一個參數是模板的檔案名稱 public function display($tplname){ $comfile = "./comps/".$tplname."_com.php"; $tplname = "./templates/".$tplname; //編譯檔案不存在 或者模板檔案有變化 才需要編譯 if(!file_exists($comfile) || filemtime($tplname)>filemtime($comfile)){ $html = file_get_contents($tplname); //要替換的部分{title} $reg = ‘/\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}/‘; //變數Regex[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]* //替換後的部分<?php echo $this->vars[‘title‘];?> $rep = "<?php echo \$this->vars[‘\\1‘];?>"; $newhtml = preg_replace($reg, $rep, $html); file_put_contents($comfile, $newhtml); } include $comfile; } }
調用模板頁面 index.php
<?phpheader(‘content-type:text/html;charset=utf-8‘);/* * 模版引擎 * PHP 超文本預先處理指令碼語言 * 自訂模板引擎 * */ //包含模板引擎類 include ‘smart.class.php‘; //建立模板引擎對象 $smarty = new Smarty(); // 串連資料庫 //執行SQL語句 // 這是從資料庫擷取的動態資料,需要在模板中顯示 $title = "This is a test"; $content = "This is content ......"; //第一個向模板中分配變數 $smarty->assign(‘title‘, $title); $smarty->assign(‘content‘, $content); var_dump($smarty); //載入指定的模板 並顯示 $smarty->display(‘c.php‘);
模板檔案頁 c.php頁面
<html><head><title>{$title}</title></head><body><h1>{$title}</h1><div>{$content}</div></body></html>
輸出結果
object(Smarty)[1] private ‘vars‘ => array (size=2) ‘title‘ => string ‘This is a test‘ (length=14) ‘content‘ => string ‘This is content ......‘ (length=22)This is a testThis is content ......
本文出自 “津沙港灣” 部落格,請務必保留此出處http://11410485.blog.51cto.com/11400485/1843240
PHP 自訂 Smarty 模板引擎類 高洛峰 細說PHP