1.Smarty3支持PHP5,不再支持PHP4
2.模板标签将不支持空格,如{ $abc }在Smarty2中可以识别的,但是3里头就不行了。
必须这样{$abc},这样是为了能够更好的支持javascript和css。
但仍然可以通过设置来支持原来的形式
$smarty->auto_literal = false;
3.增加了一下get,set方法
比如$smarty->cache_dir可以写成
$smarty->getCacheDir(), $smarty->setCacheDir('foo/')
4.Smarty使用静态函数创建实例
$smarty = Smarty::instance()
5.使模板支持PHP模板
$smarty->allow_php_templates=true 设置支持PHP模板
或者 $smarty->display('php:foo.tpl');
或者 {include file="php:foo.php"}
模板文件中可以使用PHP代码,比如 <?=$foo->escape('html')?>
6.不使用模板,直接显示文字列
$smarty->display('string:This is my template, {$foo}!');
7.模板支持计算式以及函数
{$x+$y}
{$foo = strlen($bar)}
{assign var=foo value=['y'=>'yellow','b'=>'blue']}
8.简化数组写法
{$foo['colour']} 可以写成 {$foo.colour}
9.变量名中使用变量
{$foo_{$x}} {$foo.a.{$b+4}.c}
10.调用对象的方法
{$object->method1($x)->method2($y)}
11.for循环使用in或者to
{assign var=hoge value=[a,b,c,d,e]}
{for $v in $hoge}
{$v}
{/for}
{for $x = $start to $end} ... {/for}
12.for循环使用@key @index @iteration @total @first @last
{assign var=hoge value=[a,b,c,d,e]}
{for $v in $hoge}
aaa = {$v} / {$v@key} / {$v@iteration} / {$v@total}<br />
{/for}
13.for循环中使用逗号(多个值得初始化)
{for $x=0, $y=count($foo); $x<$y; $x++} .... {/for}
14 .while循环
{while $i<10} .... {/while}
15.声明不使用缓存
{nocache} ... {/nocache}
{$foo nocache=true}
16.模板继承
parent.tpl:
{block name='title'}Default page title{/block}
child.tpl:
{extends file='parent.tpl'}
{block name='title'}Child title{/block}
也可使用以下方法继承
$smarty->display('extends:parent.tpl|child.tpl|grandchild.tpl');
注意,在子模板中,所有在{block} … {/block}之外的内容都将被忽略
17.{function}的标签
/* 定义一个函数 */
{function name=menu level=0}
<ul>
{foreach $data as $entry}
{if is_array($entry)}
<li>{$entry@key}</li>
{menu data=$entry level=$level+1}
{else}
<li>{$entry}</li>
{/if}
{/foreach}
</ul>
{/function}
/* 给函数传递的参数 */
{$menu = ['item1','item2','item3' => ['item3-1','item3-2','item3-3' =>
['item3-3-1','item3-3-2']],'item4']}
/* 调用函数 */
{menu data=$menu}
18.创建数据对象
$data = $smarty->createData();
$data->assign('foo','bar');
$data->config_load('my.conf');
$data = $smarty->createData($smarty); // 以Smarty作为父对象,创建数据对象
$data2= $smarty->createData($data); // 以data作为父对象,创建数据对象data2
19.创建模板对象
$tpl = $smarty->createTemplate('mytpl.tpl');
$tpl->assign('foo','bar');
$tpl->config_load('my.conf');
$tpl = $smarty->createTemplate('mytpl.tpl',$smarty); // 以Smarty为父对象,创建模板对象
20.capture:载入但不显示模板
载入:
{capture name=banner}
{include file='get_banner.tpl'}
{/capture}
显示:
{if $smarty.capture.banner ne ''}
<div id="banner">{$smarty.capture.banner}</div>
{/if}