二、基本语法
时间:2007-05-24 来源:panzt
1、注释 模板注释被*号包围,例如 {* this is a comment *}
2、每一个smarty标签输出一个变量或者调用某种函数.在定界符内 函数(用'{'包住)和其属性(用界符包住)将被处理和输出 {include file="header.tpl"}
3、从PHP获取变量
$smarty = new Smarty;
$smarty->assign('Contacts',
array('fax' => '555-222-9876',
'email' => '[email protected]',
'phone' => array('home' => '555-444-3333',
'cell' => '555-111-1234')));
$smarty->display('index.tpl');
index.tpl:
{$Contacts.fax}
{$Contacts.email}
{* you can print arrays of arrays as well *}
{$Contacts.phone.home}
{$Contacts.phone.cell}
OUTPUT:
555-222-9876
[[email protected]%3E 555-444-3333 %20555-111-1234][email protected]>
555-444-3333
555-111-1234
[/email]
也可以通过索引来访问数组数据
$smarty = new Smarty;
$smarty->assign('Contacts',
array('555-222-9876',
'[email protected]',
array('555-444-3333',
'555-111-1234')));
$smarty->display('index.tpl');
index.tpl:
{$Contacts[0]}
{$Contacts[1]}
{* you can print arrays of arrays as well *}
{$Contacts[2][0]}
{$Contacts[2][1]}
OUTPUT:
555-222-9876
[email protected]
555-444-3333
555-111-1234
4、修饰你的变量
范例如下:
比如:" /> 总金额:元 最终得出的输出是: 总金额:21,000 元
5、这里注意几个重点:1. 模版的位置都是以先前定义的 template_dir 为基准;2. 所有 include 进来的子模版中,其变量也会被解译。;3. include 中可以用「变量名称=变量内容」来指定引含进来的模版中所包含的变量,如同上面模版 4 的做法。
重复的区块
在 Smarty 样板中,我们要重复一个区块有两种方式: foreach 及 section 。而在程序中我们则要 assign 一个数组,这个数组中可以包含数组数组。就像下面这个例子:
首先我们来看 PHP 程序是如何写的:
test2.php:
"苹果", 2 => "菠萝", 3 => "香蕉", 4 => "芭乐");
$tpl->assign("array1", $array1);
$array2 = array(
array("index1" => "data1-1", "index2" => "data1-2", "index3" => "data1-3"),
array("index1" => "data2-1", "index2" => "data2-2", "index3" => "data2-3"),
array("index1" => "data3-1", "index2" => "data3-2", "index3" => "data3-3"),
array("index1" => "data4-1", "index2" => "data4-2", "index3" => "data4-3"),
array("index1" => "data5-1", "index2" => "data5-2", "index3" => "data5-3"));
$tpl->assign("array2", $array2);
$tpl->display("test2.htm");
?>
而模版的写法如下:
templates/test2.htm:
测试重复区块
利用 foreach 来呈现 array1
利用 section 来呈现 array1
利用 foreach 来呈现 array2
:
利用 section 来呈现 array1
index1:
index2:
index3:
执行上例后,我们发现不管是 foreach 或 section 两个执行结果是一样的。那么两者到底有何不同呢?
第一个差别很明显,就是foreach 要以巢状处理的方式来呈现我们所 assign 的两层数组变量,而 section 则以「主数组[循环名称].子数组索引」即可将整个数组呈现出来。由此可知, Smarty 在模版中的 foreach 和 PHP 中的 foreach 是一样的;而 section 则是 Smarty 为了处理如上列的数组变量所发展出来的叙述。当然 section 的功能还不只如此,除了下一节所谈到的巢状资料呈现外,官方手册中也提供了好几个 section 的应用范例。
不过要注意的是,丢给 section 的数组索引必须是从 0 开始的正整数,即 0, 1, 2, 3, ...。如果您的数组索引不是从 0 开始的正整数,那么就得改用 foreach 来呈现您的资料。您可以参考官方讨论区中的此篇讨论,其中探讨了 section 和 foreach 的用法。
相关阅读 更多 +
排行榜 更多 +