您的位置:首页 > 其它

smarty学习笔记之新手入门

2009-02-18 20:41 375 查看
1 .include_once语句:
引用文件路径,路径必需正确。
2 $smarty=new Smarty();
新建一个对象smarty, 实例化一个对象。
3 $smarty->template_dir=“”;
指定$smarty对象使用的tpl模板的路径,它是一个目录,默认目录为当前的templates的目录,实际编程中,可能要指定目录。
4 $smarty->compile_dir=””;
指定$smarty对象的编译时的目录,就是smarty编译模板的目录,linux服务器,请你确认有可写可读权限。通常chmod -R 777 filename 修改权限,默认情况下它编译目录是当前的目录下的templates_c。
5 $smarty->left_delimiter 与 $smarty->right_delimiter;
查找模板变量左右的分割符,默认情况下为{ } 为了与script中括号相区别,通常写为<{ }>.
6 $tp1->cache_dir=”./”;
模板文件缓存的位置,Smarty最大的优点在于可以缓存,这里设置缓存的目录,默认情况下当前目录下的cache目录,同上,linux确保它的可读可写性。
7 $smarty->cache-lifetime=60*60*24;
这里以秒为单位计算缓存有效的时间,第一次缓存时间到期时Smarty的caching变量设置为true时缓存将被重建。-1表示建立缓存从不过期,为0时表示每次程度执行时缓存被重新建立,上述一天。
8 $smarty->catching=true;
缓存方式三个状态。0:Smarty'默认值,表示不对模板进行缓存。1:Smarty使用cache_lifetime来决定是否结束。2:表示Smarty将使用cache被建立时使用cache_lifetime这个值,习惯上用true和false来表示是否进行缓存。
9 $smarty->assign(“name”,”张三”);
assign核心函数。对模板变量替换。
10 $smarty->display(index.tp1)
模板显示,不需要指定路径。路径在$smarty->templates(string path)中指定。

Smarty的精华所在section 和foreach循环块。
1。foreach : 循环简单数组,它是一个选择性的section循环,格式如下:
<{foreach from=$array item=array_id}>
<{foreachelse}>
<{/foreach}>
form指定循环的数组变量,item循环变量的名称,循环次数由from指定数组变量的个数决定。数组为空。执行<{foreachelse}>语句
<html>
<head><title>Test foreach</title></head>
<body>
<{foreach from=$newsArray item=newID}>
The Id:<{$newsID.newsID}>
The Content:<{$newsID.newsTitle}>
<{foreachelse}>
No content to put
<{/foreach}>
</body>
</html>

<?php
require_once("../libs/Smarty.class.php");
$smarty = new Smarty();
//$smarty->compile_check = true;
//$smarty->debugging = true;
$array[]=array("newID"=>1,"newTitle"=>"the one");
$array[]=array("newID"=>2,"newTitle"=>"the two");
$smarty->assign("newsArray",$array);
$smarty->display("index.html");
?>

2 section: 解决foreach不足产生。用于设计模板内的循环块。复杂。可完成foreach语句所完成所有的功能。Section的格式:
<{section loop= $varName[,start=$start,step=$setp,max=$max,$show=true]}>
name: section的名称,不用加$;
$loop: 要循环的变量,程度中要使用assign对这个变量进行操作。
$start: 开始循环的下标。默认为0;
$step: 每次循环下标的增数;
$show : boolean型。决定是否对于这块进行显示。默认为true;
<{section}>的属性;
index:循环下标。默认为0;
index_prev:当前下标的上一个值,默认为-1;
index_next:当前下标的下一个值,默认为1;
first:是否为第一下循环;
last:是否为最后一个循环;
iteration:循环个数;
rownum:当前行号,iteration的别名;
loop:最后一个循环号。Section的循环次数;
show:是否显示;
<{sectionelse}>处理地空循环.
<html>
<head><title>Test section</title></head>
<body>
<{section loop=$News}>
新闻编号:<{$News[loop].newID}><br>
新闻内容:<{$News[loop].newTitle}><br>
<{sectionelse}>
I am sorry
<{/section}>
</body>
</html>

<?php
require_once("../libs/Smarty.class.php");
$smarty = new Smarty();
//$smarty->compile_check = true;
//$smarty->debugging = true;

$array[]=array("newID"=>1,"newTitle"=>"the one");
$array[]=array("newID"=>2,"newTitle"=>"the two");
$smarty->assign("News",$array);
$smarty->display("index.html");
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: