smarty模板引擎類簡單工作原理
利用Smarty 模板引擎類對模板文件中的變量進行編譯,編譯過程其實就是利用正則表達式翻譯成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*\}/';
//變量正則表達式[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
<?php
header('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>
<h2>{$title}</h2>
<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 test This is content ......
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。