1.Smarty的配置:
将lib的内容复制到自己的工程,然后引入
实例化和配置Smarty基本属性:
$smarty = new Smarty();
$smarty->left_delimiter = "{"; //左定界符
$smarty->right_delimiter = "}";//右定界符 {大括号内内容由Smarty处理}
$smarty->template_dir = "tpl"; //html模版
$smarty->compile_dir = "template_c"; //模板编译生成的文件
$smarty->cache_dir = "cache";
$smarty->caching = true;
$smarty->cache_lifetime = 120;
其中界定符定义了Smarty处理的部分。
2.Smarty的基本语法:
1.变量定义和赋值
$smarty->assign(<var>,<var_value>);
$smarty->display('<tpl>')
2.注释
{*注释内容*}
3.数组变量的输出
定义:
$arr = array('articlecontent' =>array('title'=>'smarty学习','author'=>'小明'));
$smarty->assign('arr',$arr);
访问:
{$arr.articlecontent.title}
{$arr['articlecontent']['title']}</span>
4.变量调节器:
使用
{<变量>|<调节器>}
1.调节器例如capitalize是首字母大写 lower upper
2.字符串连接:{<原始字符串>|cat:<要连接的字符串>} 可多次连接,多次连接后面直接加 :<内容>:<内容>(冒号 内容 冒号 内容...)
3.日起格式化 date_format
{$yesterday|date_format} 可带参数
php的函数time可以得到Unix时间戳,即从1970年1月1日至今的秒数
格式化方式为
{$time|date_format:"%B %e %Y %H:%M:%S"}
时间为格林威治时间
B为月,e为日,Y为年
4.为未赋值或空变量设定默认值
|default:<默认值>
5.escape转码
url可能会影响php等脚本语言正常运转,对网址转码
对url转码:
{$url|escape:'url'}
6.nl2br表示将正常换行符转化为br标签,可以实现字符串换行
3.条件判断
eq ==
neq !=
gt >
lt <
注意修饰符和变量常量空格隔开
例子:
{if $score gt 90}
优秀
{elseif $score gt 60}
及格
{else}
不及格
{/if}
4.循环语句
{section name=<element_index> loop=<要循环的数组>}
{/section}
例如要打印如下数组的内容:
$way = array(
array(
"title" => "article1",
"author" => "ywx",
"content" => "ich mag dich!"
),
array(
"title" => "article2",
"author" => "dw",
"content" => "ich mag dich?"
)
);//$way在smarty中配置为$dich
在php脚本中如下操作:
{section name=index loop=$dich}
{$dich[index].title}
{$dich[index].author}
{$dich[index].content}
<br/>
{/section}
foreach的用法:
{foreach item=<item> from=<source>}
{$item.index}
{foreachelse}
{/foreach}