一、 什么是smarty?
smarty 是一个使用PHP写出来的模板PHP模板引擎,可以理解成是一个用php编写的类。它提供了逻辑与外在内容的分离,简单的讲,目的就是要使用PHP程序员同美工分离,使用的程序员改变程序的逻辑内容不会影响到美工的页面设计,美工重新修改页面不会影响到程序的程序逻辑。
二、smarty优点:
1. 速度:采用smarty编写的程序可以获得最大速度的提高,这一点是相对于其它的模板引擎技术而言的。
2. 编译型:采用smarty编写的程序在运行时要编译成一个非模板技术的PHP文件,这个文件采用了PHP与HTML混合的方式,在下一次访问模板时将WEB请求直接转换到这个文件中,而不再进行模板重新编译(在源程序没有改动的情况下
3. 模板中可以使用if/elseif/else/endif。在模板文件使用判断语句可以非常方便的对模板进行格式重排。
4. 缓存技术:smarty选用的一种缓存技术,它可以将用户最终看到的HTML文件缓存成一个静态的HTML页,当设定smarty的cacheing属性 为true时,在smarty设定的cachetime期内将用户的WEB请求直接转换到这个静态的HTML文件中来,这相当于调用一个静态的HTML文 件。
5. 插件技术:smarty可以自定义插件。插件实际就是一些自定义的函数。
三、不适合使用smarty的地方:
1. 需要实时更新的内容。例如像股票显示,它需要经常对数据进行更新,这类型的程序使用smarty返而会使模板处理速度变慢。
2. 小项目。小项目因为项目简单而美工与程序员兼于一人的项目,使用smarty返而会丧失php开发迅速的优点。
四、smarty配置:
1 基本配置
require_once(“include/smarty/Smarty.class.php”);
$smarty = new smarty;
$smarty->left_delimiter = '{{';
// 定义替换符号
$smarty->right_delimiter = '}}';
// 定义替换符号
$smarty->caching = true;
// 设置cache有效
$smarty->template_dir = FNAME."templates/";
// 模版文件存放路径
$smarty->cache_dir = FNAME."cache/";
// 缓存存放路径
$smarty->config_dir = FNAME."configs/";
//smarty 配置文件存放路径
2 高级配置
require_once 'include/smarty/Smarty.class.php';
$smarty = new smarty;
$smarty->left_delimiter = '{{';
// 定义替换标记
$smarty->right_delimiter = '}}';
// 定义替换标记
$smarty->debugging = false;
// 关闭掉调试控制台
$smarty->force_compile = false;
// 强迫编译变量,强迫Smarty每次调用(重新)编译模板
$smarty->compile_check = true;
// 每次调用PHP应用程序,Smarty 会试着查看自上次编译时间以来,当前模板是否被修改过.如果修改过了,它会重新编译那个模板 .
$smarty->caching = true;
//设置cache有效
$smarty->compile_dir = FNAME."templates_c/";
//smarty 编译后的文件存放路径
$smarty->template_dir = FNAME."templates/";
// 模版文件存放路径
$smarty->cache_dir = FNAME."cache/";
// 缓存存放路径
$smarty->config_dir = FNAME."configs/";
//smarty 配置文件存放路径
$smarty->plugins_dir = FNAME."phpcode/include/smarty/smartyActive/"; // 自定义函数路径,默认在smarty/plugs下
$smarty->cache_lifetime = 600;
// 定义模板缓存有效时间段的长度
$smarty->config_overwrite = false;
// 如果设该变量为真,则从配置文件中读取出来的变量将会互相覆盖.否则,变量将会放到一个数组中
五、smarty在模板中的使用:
本节通过几个实例来讲一讲smarty的使用,smarty模板通常使用.tpl来标识,也可以将扩展名直接写成.html。
实例1:
先来看一个简单的例子 。
index.html <html> <head> <title>{{$webtitle}}</title> </head> <body> <-- Begin assign --><br> {{$name}} <br> {{literal}} {{ 李四 }} {{/literal}} <br> <-- End assign --> {{include file="foot.html"}} </body> </html> |
上边的这个例子是一个html模板,其中:
1. {{include file="xxx.html"}}使用此句将一个模板文件包含到当前页面中,例子中将在网站中公用事的head.html与foot.html进行了包 含,你可以这样想,使用这一句将xxx.html中的内容全部复制在当前语句处。当然,你不使用这一句也可以,将XXX.html中的内容复制到当前语句 处也是完全可以了。
2.{{$name}}: 模板变量,smarty中的核心组成,采用smarty定义的左边界符{{与右边界符}}包含着、以PHP变量形式给出,在smarty程序中将使用 $smarty->assign("name", "张三");将模板中的$name替换成“张三”三个字。
3. 当有类似{{李四}}这样的特殊标记不希望被smarty替换时,需要这样来标识
{{literal}}{{ 李四}}{{/literal}}这样位于{{literal}}与{{/literal}}之间的内容就不会被smarty解析。
整个实例源程序如下:
index.php <? include_once("include/config.inc.php"); $smarty->assign("webtitle","smarty"); $smarty->assign("name"," 张三 "); $smarty->display("index.html"); ?> |
foot.html <hr> <center> CopyRight(C) by {{$smarty.now}}</center> <hr> |
index.html <html> <head> <title>{{$webtitle}}</title> </head> <body> <-- Begin assign --><br> {{$name}} <br> {{literal}} {{ 李四 }} {{/literal}} <br> <-- End assign --> {{include file="foot.html"}} </body> </html> |
实例2:
这个例子是综合使用smarty模板参数的一个例子,这些参数用来控制模板的输出,只选出其中几个,其它的参数可以去看参考。
tplpar.html <html> <head> <title>{{$webtitle}}</title> </head> <body style="font-size:12px"> 1. 第一句首字母要大写: {{$str1|capitalize}}<br> 2. 第二句模板变量 + 张三:{{$str2|cat:"张三 "}}<br> 3. 第三句输出当前日期:{{$str3|date_format:"%Y年%m月%d日 "}} <br> 4. 第五句要让它缩进8个空白字母位,并使用"*"取替这8个空白字符: <br> {{$str4|indent:8:"*"}}<br> 5. 第六句把YMF@163.com全部变为小写: {{$str5|lower}}<br> 6. 第七句把变量中的name替换成:张三:{{$str6|replace:"name":"张三 "}}<br> 7. 截取字符串,并用"..."代替 :{{$str7|truncate:8:"...":true}}<br> 8.去除html标签: {{$str8|strip_tags}} </body> </html> |
tplpar.php <? include_once("include/config.inc.php"); $smarty->assign("webtitle","smarty 参数例子 "); $smarty->assign("str1", "my name is zhang san"); $smarty->assign("str2", "我的名字叫: "); $smarty->assign("str3", time()); $smarty->assign("str4", "前边8个 *"); $smarty->assign("str5", "YMF@163.com"); $smarty->assign("str6", "this is name,this is name"); $smarty->assign("str7", "一起研究smarty吧 "); $smarty->assign('str8', "Blind Woman Gets <font face=/"helvetica/">New Kidney</font> from Dad she Hasn't Seen in <b>years</b>."); $smarty->display("tplpar.html"); ?> |
实例 3.
smarty中的函数应用
tplfunction.html <html> <head> <title>{{$webtitle}}</title> </head> <body style="font-size:12px"> 1.html_checkboxes 函数 <br> {{html_checkboxes name="id" options=$cust_checkboxes checked=$customer_id separator="<br />"}} <br> 2.html_radios 函数 <br> {{html_radios name="id" options=$cust_radios checked=$customer_id separator="<br />"}} <br> 3.html_options 函数 <br> <select name=customer_id> {{html_options options=$cust_options selected=$customer_id}} </select> <br> 4.html_select_date 函数(默认形式 ) <br> {{html_select_date}} <br> 5.html_select_date函数(可处理形式 ) <br> {{html_select_date prefix="StartDate" start_year="-5" end_year="+1" display_days=true month_format="%m" day_format="%d" field_order="YMD" }} <br>参数说明:prefix 下拉框的name前缀,如该下拉框的name分别为 StartDateYear StartDateMonth StartDateDay<br> start_year 开始的年份,为当前年份 -5<br> end_year 结束年份,为当前年份 +1<br> display_days 是否显示日的选择,同理会有 display_month display_year<br> month_format 月份的显示格式 <br> day_format 日期的显示格式 <br> field_order 下拉框的顺序,即年月日的排列顺序 <br> 6.接收变量函数 <br> $smarty.get.id:接收get过来的id的值 {{$smarty.get.id}}<br> $smarty.post.id:接收post过来的id的值 {{$smarty.post.id}}<br> $smarty.request.id:接收request过来的id的值 {{$smarty.request.id}}<br> $smarty.cookies.id:接收cookie中名为id的值 {{$smarty.cookies.id}}<br> $smarty.session.id:接收session中名为id的值 {{$smarty.session.id}}<br> $smarty.const.FNAME:取出php中定义名为FNAME的常量: {{$smarty.const.FNAME}}<br> $smarty.now:取出当前UNIX时间戳 :{{$smarty.now}}<br> </body> </html> |
tplfunction.php <? include_once("include/config.inc.php"); $smarty->assign("webtitle","smarty 函数例子 "); //html_checkbox函数 $smarty->assign('cust_checkboxes', array( 1000 => 'Joe Schmoe', 1001 => 'Jack Smith', 1002 => 'Jane Johnson', 1003 => 'Charlie Brown')); $smarty->assign('customer_id', 1001); //html_radios 函数 $smarty->assign('cust_radios', array( 1001 => 'Joe Schmoe', 1002 => 'Jack Smith', 1003 => 'Jane Johnson', 1004 => 'Charlie Brown')); $smarty->assign('customer_rid', 1001); //html_options 函数 $smarty->assign('cust_options', array( 1001 => 'Joe Schmoe', 1002 => 'Jack Smith', 1003 => 'Jane Johnson', 1004 => 'Charlie Brown')); $smarty->assign('customer_id', 1001); $smarty->display("tplfunction.html"); ?> |
实例 4
模版控制应用 , 模版中的控制一般有一下几种常用函数:section、foreach、if elseif else,这个例子讲一下他们的用法。
tplcontrol.html <html> <head> <title>{{$webtitle}}</title> </head> <body style="font-size:12px"> 1.section 的用法(php数组key必须从0开始 )<br> <table> {{section name=c_sec loop=$customer}} <tr bgcolor="{{cycle values='#eeeeee,#d0d0d0'}}"> <td>{{$smarty.section.c_sec.index}}</td> <td>id:{{$customer[c_sec].id}}</td> <td>name:{{$customer[c_sec].name}}</td> </tr> {{/section}} <tr><td colspan="3">共有{{$smarty.section.c_sec.total}}个用户 </td></tr> </table> <br> 2.foreach的用法 <br> <table> {{foreach key=key name=outer item=contact from=$customer}} <tr> <td>{{$key}}</td> <td>{{$contact.id}}</td> <td>{{$contact.name}}</td> </tr> {{/foreach}} </table> <br> 3.if,elseif,else的用法 <br> <table> <tr> <td>{{if $exam eq 0}}exam=0{{elseif $exam eq 1}}exam=1{{else}}exam=????{{/if}}<td> </tr> </table> <br> 4.section 嵌套(需要php数组为四维) <table> {{section name=s_sec loop=$sort}} <tr bgcolor="{{cycle values='#eeeeee,#d0d0d0'}}"> <td>{{$smarty.section.s_sec.index}}</td> <td>id:{{$sort[s_sec].id}}</td> <td>name:{{$sort[s_sec].name}}</td> </tr> <tr><td width="10px"> </td><td colspan="2"> <table width="100%"> {{section name=sub_sec loop=$sort[s_sec].sub}} <tr bgcolor="{{cycle values='#eeeeee,#d0d0d0'}}"> <td>{{$smarty.section.sub_sec.index}}</td> <td>id:{{$sort[s_sec].sub[sub_sec].id}}</td> <td>name:{{$sort[s_sec].sub[sub_sec].name}}</td> </tr> {{/section}} </table> </td></tr> {{/section}} </table> 5. 模版文件中引用php代码,采用{php}作为标记 {{php}} for($i=0;$i<5;$i++){ echo $i."<br>"; } {{/php}} </body> </html> |
tplcontrol.php <? include_once("include/config.inc.php"); $smarty->assign("webtitle","smarty 控制例子 "); $customer =array( 0 => array("id"=>'1000',"name"=>'Joe Schmoe'), 1 => array("id"=>'1001',"name"=> 'Jack Smith'), 2 => array("id"=>'1002',"name"=> 'Jane Johnson'), 3 => array("id"=>'1003',"name"=> 'Charlie Brown') ); $smarty->assign('customer',$customer); //if else if else $exam = 1; //section 树型结构数组 $sort =array( 0 => array( "id"=>'1000', "name"=>' 分类 A', "sub"=>array( 0 => array( "id"=>"1", "name"=>"A1" ), 1=> array( "id"=>"2", "name"=>"A2" ), 2 => array( "id"=>"3", "name"=>"A3" ), 3=> array( "id"=>"4", "name"=>"A4" ) ) ), 1 => array( "id"=>'1001', "name"=> '分类 B', "sub"=>array( 0 => array( "id"=>"1", "name"=>"B1" ), 1=> array( "id"=>"2", "name"=>"B2" ), 2 => array( "id"=>"3", "name"=>"B3" ), 3=> array( "id"=>"4", "name"=>"B4" ) ) ), 2 => array( "id"=>'1002', "name"=> '分类 C', "sub"=>array( 0 => array( "id"=>"1", "name"=>"C1" ), 1=> array( "id"=>"2", "name"=>"C2" ) ) ), 3 => array( "id"=>'1003', "name"=> '分类 D', "sub"=>array( 0 => array( "id"=>"1", "name"=>"D1" ) ) ) ); $smarty->assign("sort",$sort); $smarty->assign('exam',$exam); $smarty->display("tplcontrol.html"); ?> |
六 、 Smarty 缓存的应用
1. 使用缓存
首先保证$smarty->caching=true,这样smarty生成的缓存文件就放入了设置的cache_dir文件夹中。
2. 清除缓存
clear_all_cache();//清除所有缓存
clear_cache('index.tpl');// 清除index.tpl的缓存
clear_cache('index.tpl',cache_id);// 清除指定id的缓存
3. 建立缓存目录分级
用于解决缓存文件过大的问题
$smarty->use_sub_dirs = true;
七 、 smarty 自建函数
定义规则:如文件名称为function.dataop.php,则文件内部的函数名称必须为
smarty_function_dataop 。
实例 1
编写函数 smarty_function_dataop ,用来显示常用的下拉框,如:身份、职业等。
function.dataop.php <?php function smarty_function_dataop($params, &$smarty) { if (!isset($params['key'])) { $smarty->trigger_error("checkid: missing 'key' parameter"); return ''; } $ret=''; $key=strtolower($params['key']); switch($key) { case "jobpos": $data=array( "-1"=>" 请选择 ", "100"=>'工程师 ', "101"=>'IT人士 ' ); $show=$data; break; case "hangye": $data=array( "-1"=>"请选择 ", "142"=>'外企 ', "100"=>'国营企业 ', "101"=>'国家机关 ' ); $show=$data; break; case "prov": $data=array( "999"=>"-----" , "100"=>"北京 " , "101"=>"辽宁 " ); $show=$data; break; } if($params[op]=='show') { foreach($data as $k=>$v) if($params['value']==$k) $ret.="$show[$k] "; } elseif($params[op]=="select") { foreach($data as $k=>$v){ if($params['value']==$k) $ret.="<option value='$k' selected>$show[$k]</option>"; else $ret.="<option value='$k'>$show[$k]</option>"; } } elseif($params[op]=="radio"){ foreach($data as $k=>$v){ if($params['value']==$k) $ret.="<input type='radio' value='$k' checked>$show[$k]; else $ret.="<input type='radio' value='$k'>$show[$k]</option"; } } elseif($params[op]=="checkbox"){ foreach($data as $k=>$v) if($params['value']==$k) $ret.="<input type='checkbox' value='$k' checked>$show[$k]"; else $ret.="<input type='checkbox' value='$k'>$show[$k]</option>"; } return $ret; return ''; } ?> |
tplactive.html <html> <head> <title>{{$webtitle}}</title> </head> <body style="font-size:12px"> 1. 自定义函数 ,smarty_function_dataop<br> <table><tr><td> <select name="prov"> {{dataop value='100' op='select' key='prov'}} </select> </td></tr></table> <br> <table><tr><td> {{dataop op='radio' value='100' key='jobpos'}} </td></tr></table> <br> <table><tr><td> {{dataop op='checkbox' value='100' key='hangye'}} </td></tr></table> <br> </body> </html> |
实例 2
编写块函数 smarty_block_translate , 用来控制定义的块中的内容等。
block.translate.php <? function smarty_block_translate ($params, $content, &$smarty, &$repeat) { if (isset($content)) { if($params[lang] == "en"){ $translation = "This is a example for block"; } else{ $translation = "这是一个block的例子 "; } return $translation; } //将该函数注册到{{translate}}......{{/translate}}这个block中 $smarty->register_block('translate', 'smarty_block_translate'); }?> |
do_translation.html <? {{translate lang='en' key='hr' a="1"}}Hello, world!{{/translate}} |