Smarty學習筆記(一)


一.模板技術介紹及自定義模板引擎

1.模板技術:php中將業務邏輯同頁面視圖分開
2.自定義模板引擎:
a.模板類:
<?php
	class MyTpl {
		private $template_dir;
		private $compile_dir;
		private $tpl_vars=array();

		public function __construct($template_dir="./templates", $compile_dir="./templates_c"){
			$this->template_dir=rtrim($template_dir,"/").'/';
			$this->compile_dir=rtrim($compile_dir, "/").'/';
		}

		public function assign($tpl_var, $value=null){
			if($tpl_var!="")
				$this->tpl_vars[$tpl_var]=$value;
		}

		public function display($fileName){
			$tplFile=$this->template_dir.$fileName;

			if(!file_exists($tplFile)){
				return false;
			}

			$comFileName=$this->compile_dir."com_".$fileName.".php";

			if(!file_exists($comFileName) || filemtime($comFileName) < filemtime($tplFile)){
				$repContent=$this->tpl_replace(file_get_contents($tplFile));

				file_put_contents($comFileName, $repContent);	
			}

			include $comFileName;
			
		}

		private function tpl_replace($content){
				$pattern=array(
						'/\<\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}\>/i'
					);

				$replacement=array(
					'<?php echo $this->tpl_vars["${1}"]; ?>'
					);
			
				$repContent=preg_replace($pattern, $replacement, $content);

				return $repContent;
		}

	}


b.界面視圖:

<html>
	<head>
		<title><{ $title   }></title>
	</head>

	<body>
		<div>
			<{$content}>
		</div>	
	</body>

</html>

c:業務邏輯:
<?php
	include "mytpl.class.php";
	
	$tpl=new MyTpl("./templates/", "./templates_c");

	$title="這是從數據庫中獲取的標題";
	$content="這是從數據庫中獲取的文章內容";

	$tpl->assign("title", $title);
	$tpl->assign("content", $content);

	$tpl->display("tpl.html");

二.smart模板技術

1.在samrt模板中使用變量
注意事項:關於數組,關聯則用.取,索引則用下標取

2.在配置文件中給模板變量
模板的外觀(界面設計的變量)
要使用 $tpl->configs_dir="目錄"  //指定配置文件存放的目錄
在模板中要使用 <{configs_load file="view.conf"}> 加載view.conf配置文件
使用section="區域"   [設置區域]
<{#border#}>
<{$smarty.config.border}>

3.在samrty模板中使用自定義函數
   兩種方式:一種是使用註冊的方式, 註冊函數和塊。 另一種是使用Smarty插件的功能加入函數和塊。
在模板中使用PHP的函數:<br>


<input type="text" name="username" value="zhangsan" size="30"><br>
<input size="30" name="username" type="text" value="lisi"> <br>

<{hello num=10 content="11111 $int 11111111" size="7" color=$color }> 
<{hello content="222 `$arr.one` 2222" num=5 size=5 color="green"}>

<font color="red" size="5">
	aaaaaaaaaaa<br>
</font>

<{world num=3 color="blue" size="7"}>
	wwwwwwwwww<br>
<{/world}>

<{world color="#ff00ff" size="5" num="4"}>
	xxxxxx<{$var}>xxxxxxxxx<br>
<{/world}>

<?php
	require "init.inc.php";



	$tpl->register_function("hello", "demo");

	function demo($args){
		$html="";

		for($i=0; $i<$args["num"]; $i++){
			$html.='<font size="'.$args["size"].'" color="'.$args["color"].'">'.$args["content"]."</font><br>";
		}

		return $html;
	}

	$tpl->register_block("world", "test");
	
	function test($args, $content, &$a, &$b){
		$html="";

		for($i=0; $i<$args["num"]; $i++){
			$html.='<font size="'.$args["size"].'" color="'.$args["color"].'">'.$content."</font><br>";
		}

		return $html;
	}

	$tpl->assign("var", "@@@@@@@@@@");
	$tpl->assign("color", "blue");
	$tpl->assign("int", "#########");
	$tpl->assign("arr", array("one"=>"9999", "8888"));

	$tpl->display("test.tpl");

在smarty中的plugins下添加:
<?php
	function smarty_function_hello($args, &$smarty){
		$html='';

		for($i=0; $i<$args["num"]; $i++){
			$html.='<font color="'.$args["color"].'" size="'.$args["size"].'">'.$args["content"].'</font><br>';
		}

		return $html;
	}

<?php
	function smarty_block_world($args, $content, &$smarty){
		$html='';


		for($i=0; $i<$args["num"]; $i++){
			$html.='<font color="'.$args["color"].'" size="'.$args["size"].'">'.$content.'</font>';
		}


		return $html;	
	}



4.smarty中的變量調節器
在Smarty文件中的變量後面使用 "|"後面加函數名,這個函數第一個參數就是這個變量,如果有其它參數, 使用“:”加參數, 多個參數使用":"分開
例如:{<$str|functionname:parma1:parma2>}
<?php
	function smarty_modifier_todx($str, $xx){
		switch($xx){
			case "lower":
				$str=strtolower($str);
				break;
			case "upper":
				$str=strtoupper($str);
				break;

			case "first":
				$str=ucfirst($str);
				break;

		}

		return $str;
	}

5.smarty中的內建函數
在模板中的調用方式都和使用HTML標記類似
Smarty內部的函數,只能按手冊提供的方式使用,不可以改,也不能添和刪除
比如: 流程控制 if  , 數組的遍歷, 以及 文件件包含,配置文件導入都要使用Smarty的內建函數幫我們完成。

foreach,
和PHP的foreach用法相同,編譯成了foreach
foreachelse
如果遍歷的數組沒有,或數組爲空則執行這裏

section,sectionelse 
和foreach一樣,也是可以遍歷數組
是編譯成for循環處理數組
一、效率要比使用foreach要高
二、功能要比foreach要多
建議使用section而不使用foreach去處理數組
注意:它不能遍歷關聯數組,只能是索引數組並且要是下標連續的

<?php
	include "init.inc.php";

	$tpl->assign("var", 3);

	$mysqli=new mysqli("localhost", "root", "123456", "xsphpdb");

	$result=$mysqli->query("select * from shops order by id");



	$data=array();

	while($row=$result->fetch_assoc()){
		$row["sub"]=array(array("one"=>"aaaaa"), array("one"=>"bb"));
		$data[]=$row;
		
	}

	$tpl->assign("data", $data);
 
	$tpl->display("test.tpl");

<table align="center" border="1" width="800">
	
	<{foreach from=$data item="row" name="outer"}>
		
		<{if $smarty.foreach.outer.iteration is even }>
			<tr bgcolor="#cccccc">
		<{elseif $smarty.foreach.outer.first}>
			<tr bgcolor="red">
		<{elseif $smarty.foreach.outer.last}>
			<tr bgcolor="blue">
		<{else}>
			<tr>
		<{/if}>
			<td><{$smarty.foreach.outer.iteration}></td>
			<{foreach from=$row item="col" name="inner"}>
				<td> <{$col}></td>
			<{/foreach}>
		</tr>	
	<{foreachelse}>
		數組中沒有數據
	<{/foreach}>

<table align="center" width="800" border="1">
	<{section loop=$data name="ls" start="10" step="3" max="10"}>
		
		
		<tr>
			<td><{$smarty.section.ls.index}></td>
			<td><{$smarty.section.ls.rownum}></td>
			<td><{$data[ls].id}></td>
			<td><{$data[ls].name}></td>
			<td><{$data[ls].price}></td>
			<td><{$data[ls].num}></td>
			<td><{$data[ls].desn}></td>
			<td><{$data[ls].sub}></td>
			<td>
				<{section loop=$data[ls].sub name="lsin"}>
					##<{$data[ls].sub[lsin].one}><br>
				<{/section}>
			</td>
		</tr>
		
	<{sectionelse}>	
		數組中沒有數據
	<{/section}>
</table>

6.smarty中的緩存技術

Smarty緩存和網頁表態化一樣, 使用Smarty緩存使用非常方便
1. 需要開啓緩存
2. 指定一下緩存的時間
3. 指定緩存文件保存位置
開啓這些內容只需要爲Smarty的屬性初使化即可
注意:
1. 一個模板只能有一個緩存文件,如果一個模板的多個文章,則需要每個文章有一個緩存
$tpl->display("test.tpl", cacheid);
第二個參數,每變化一個值就會有一個不同的緩存(最好使用$_SERVER["REQUEST_URI"])
2. 一定要處理,如果有緩存了就不要執行連接數據庫和到數據庫中操作數據表了。
使用smarty中的is_cached()方去判斷,它的用法和display()相同

局部緩存設置
使用一個塊標記完成
        清除緩存功能 


<?php
	
	define(ROOT, "C:/AppServ/www/xsphp/");
	include ROOT."libs/Smarty.class.php";

	$tpl=new Smarty;
	$tpl->template_dir=ROOT."tpl/";  //模板文件
	$tpl->compile_dir=ROOT."com";    //生成編譯後的文件
	$tpl->config_dir=ROOT."configs"; //配置文件
	$tpl->caching=1;  //在開發階段不要開,運行階段再開啓
	$tpl->cache_dir=ROOT."cache";
	$tpl->cache_lifetime=10;
	$tpl->left_delimiter="<{";
	$tpl->right_delimiter="}>";
<?php
	header("Content-Type:text/html;charset=utf-8");
	include "init.inc.php";
	include "page.class.php";
	
	if(!$tpl->is_cached("test.tpl",$_SERVER["REQUEST_URI"])){

		$mysqli=new mysqli("localhost", "root", "123456", "xsphpdb");


		$result=$mysqli->query("select id from shops");

		$page=new Page($result->num_rows, 5);

		$result=$mysqli->query("select * from shops order by id {$page->limit}");

		$data=array();

		while($row=$result->fetch_assoc()){
			$data[]=$row;
		}

		$tpl->assign("data", $data);
		$tpl->assign("fpage", $page->fpage());

		echo date("Y-m-d H:i:s")."<br>";
	}

	$tpl->assign("date", date("H:i:s"));

	

	$tpl->display("test.tpl", $_SERVER["REQUEST_URI"]);

//	$tpl->clear_all_cache();

<table align="center" border="1" width="800">
	<caption><h1>SHOPS<{nocache}><{$date}><{/nocache}></h1></caption>
	<tr>
		<{nocache}>
		<th>編號</th>
		<th>名稱</th>
		<th>價格</th>
		<th>數量</th>
		<th>介紹</th>
		<{/nocache}>
	</tr>

	<{section loop=$data name="ls"}>	
		<tr>
			<td><{$data[ls].id}></td>
			<td><{$data[ls].name}></td>
			<td><{$data[ls].price}></td>
			<td><{$data[ls].num}></td>
			<td><{$data[ls].desn}></td>
		</tr>
	<{sectionelse}>
		<tr><td colspan="5">沒有商品</td></tr>
	<{/section}> 

		<tr>
			<td colspan="5" align="right"><{$fpage}></td>
		</tr>
</table>

<?php
	function smarty_block_nocache($params, $content, &$s){
		return $content;
	}





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