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;
	}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值