我對smarty模板引擎的探索

他的流程就是

請求

-> b.php文件中  綁定變量 ,展示模板

-> smarty.php文件中的步驟

         1 讀取靜態文件 a.html中的所有內容

         2 正則替換這個靜態文件a.html上的特定字符,如{$title}

         3 替換完之後再把替換後的內容,生成爲一個文件a.html.php(用作前端展示的)

         4然後再包含這個新生成的文件

-> 展示這個替換過後的頁面

未處理過的前端頁面

a.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>{$title}</title>
</head>
<body>
	{$contens}
</body>
</html>

 

開始展示模板

b.php

<?php

	include './smarty.php';

	$smarty = new Smarty;

	$tit = '標題';// 數據庫的數據

	$contens = '內容';// 數據庫的數據


	$smarty->assign('title', $tit);
	$smarty->assign('contens', $contens);
	$smarty->display('a.html');

smarty 類的方法

smarty.php

<?php

class Smarty {


	private $vars = array();

	/**
	 * 分配變量
	 * @param  [type] $varname  [description]
	 * @param  [type] $varvalue [description]
	 * @return [type]           [description]
	 */
	public function assign($varname, $varvalue) {

		$this->vars[$varname] = $varvalue;

	}

	/**
	 * 顯示模板
	 * @param  [type] $tplname [description]
	 * @return [type]          [description]
	 */
	public function display($tplname) {
		
		$html = file_get_contents($tplname);//打開這個文件,這個文件是 a.html

		$zhengZeTiaoJian = '/\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}/';// 正則替換變量的條件

		$rep = "<?php echo \$this->vars['\\1']; ?>";//如果是\\1的話就是是否有$,\\0和$0代表完整的模式匹配文本,當然是要配合preg_replace() 這個函數來做
		$newhtml = preg_replace($zhengZeTiaoJian, $rep, $html);//如果html這個頁面有(變量),就把他寫進\\1裏面,\\1代表是是否有$,有就去除,如果是\\0的話就是全部匹配

		file_put_contents($tplname.".php", $newhtml);//把文件存進去

		include $tplname.'.php';//顯示這個文件
	}
}

 

生成的模板文件如下:

a.html.php  這個文件,就是用來展示給用戶看的

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title><?php echo $this->vars['title']; ?></title>
</head>
<body>
	<?php echo $this->vars['contens']; ?>
</body>
</html>

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章