今天学的传说中smarty模版,为什么使用smarty,smarty的好处是什么:
将一些判断放在了HTML模板文件中,本身用模板的目的就是分开PHP代码和HTML,
这样不仅PHP中有判断,HTML也有判断,在一定程度上(对于美工设计或页面设计人员)加大了开发难度。
当然,在小型和一部分中型web开发中这样做是可以的。但在大型WEB项目中,这样做就不好了。
smarty原理
1>访问php文件
2>在php文件中加载模版引擎
3>分配变量给smarty模版
4> 将模版导入(可以有多个模版,例如QQ空间的皮肤)
5>将模版变量替换掉
6>生成编译的文件
7>在php里通过模版引擎将编译后的文件输出—>ok!
下边给个实例:::::::::
假设smarty解压安装在网站根目录的smarty目录下 1.smarty的配置 首先,使用smarty第一件事是先配置好,一般有以下9行代码
require_once("smarty/libs/Smarty_class.php"); //把smarty的类定义文件包含进来 $smarty=new smarty(); $smarty->config_dir="smarty/libs/Config_File.class.php"; $smarty->caching=false; //是否使用缓存,项目在调试期间,不建议启用缓存 $smarty->cache_dir="smarty_cache/"; //缓存文件夹 $smarty->template_dir="smarty_tpl"; //模板文件夹 $smarty->compile_dir="smarty_compile"; //编译文件夹 $smarty->left_delimiter="<{"; // 标签符定义不是必要的,smarty默认是使用"{"和"}",强烈建议更换。 //因为如果smarty的标签刚好在javascript语句里面时,冲突的可能性很大 $smarty->right_delimiter="}>";
以上的9行代码可以放在一个独立的文件,需要使用smarty的页面引用进来即可
2. smarty的使用 smarty替换标签的语法: smarty->assign("标签名","值"); smarty->display("index.html"); //显示内容,index为模板文件名假定模板文件里面有一个标签 <{ $user_name }> (注意:标签里面的变量必须带$) 那么在PHP文件可以: $new_name="Joan"; smarty->assign("user_name",$new_name); (注意:在此时,user_name是不带$的) smarty->display("index.html"); //显示内容,index为模板文件名
3. smarty的循环 循环的使用在php文件像处理普通标签一样处理 模板文件代码: <table border=1 width=500> <{section name=s loop=$stu}> <tr> <td> <{$stu[s]}> </td> </tr> <{/section}> </table>那么在PHP文件可以: 假如有一个数组,或一个记录集 $rs $smarty->assign("stu",$rs); $smarty->display("index.html"); //在PHP文件处理循环标签和普通标签没什么区别。
4. smarty的if 语法 模板文件 <{if $my_r>500 }> <{$my_r}> <{/if}>php文件:
$aa=123; $smarty->assign("my_r",$aa); $smarty->display("in.html"); 上例中,如果$aa>500,my_r的标签就能显示出来,否则不显示。 <{ if 条件 }> //此处的条件不要加括号,也不要像basic语言那样在后面加 then
<{/if}>
5. smarty循环配合if 使用实例
PHP文件 ---------------------------------- $aa[0]=123; $aa[1]=456; $aa[2]=789; $smarty->assign("my_r",$aa); $smarty->display("in.html");
模板文件 ------------------------------------------------------ <{ section name=s loop=$my_r }> <{if $my_r[s]>200 }> <{$my_r[s]}> <{else}> 小于200 <{/if}> <br> <{/section}> ----------------------------------------------- 上例中,只显示大于200的数值
<{ section name=s loop=$my_r }> <{if $my_r[s]=="456" }> //这是字符型的实例,用== <{$my_r[s]}> <{else}> Not <{/if}> <br> <{ /section }>