Smarty 是什么?
为什么要使用它?
用例和工作流
语法比较
模板继承
最佳做法
快速入门
Smarty 有多种不同类型的变量。变量类型取决于它之前或包含在什么符号中。
Smarty 中的变量可以直接显示,也可以用作函数、
示例 4.1. 示例变量
{$Name}
{$product.part_no} <b>{$product.description}</b>
{$Contacts[row].Phone}
<body bgcolor="{#bgcolor#}">
查看已分配 Smarty 变量的一种简单方法是使用调试控制台。
通过在前面前缀美元 ($) 符号引用已分配的变量。
示例 4.2. 已分配变量
PHP 代码
<?php
$smarty = new Smarty();
$smarty->assign('firstname', 'Doug');
$smarty->assign('lastname', 'Evans');
$smarty->assign('meetingPlace', 'New York');
$smarty->display('index.tpl');
?>
index.tpl 源
Hello {$firstname} {$lastname}, glad to see you can make it.
<br />
{* this will not work as $variables are case sensitive *}
This weeks meeting is in {$meetingplace}.
{* this will work *}
This weeks meeting is in {$meetingPlace}.
上述内容将输出
Hello Doug Evans, glad to see you can make it. <br /> This weeks meeting is in . This weeks meeting is in New York.
您还可以通过在句点 "." 符号之后指定键来引用关联数组变量。
示例 4.3. 访问关联数组变量
<?php
$smarty->assign('Contacts',
array('fax' => '555-222-9876',
'email' => 'zaphod@slartibartfast.example.com',
'phone' => array('home' => '555-444-3333',
'cell' => '555-111-1234')
)
);
$smarty->display('index.tpl');
?>
index.tpl 源
{$Contacts.fax}<br />
{$Contacts.email}<br />
{* you can print arrays of arrays as well *}
{$Contacts.phone.home}<br />
{$Contacts.phone.cell}<br />
这将输出
555-222-9876<br /> zaphod@slartibartfast.example.com<br /> 555-444-3333<br /> 555-111-1234<br />
您可以通过其索引引用数组,非常类似于原生 PHP 语法。
示例 4.4. 按索引访问数组
<?php
$smarty->assign('Contacts', array(
'555-222-9876',
'zaphod@slartibartfast.example.com',
array('555-444-3333',
'555-111-1234')
));
$smarty->display('index.tpl');
?>
index.tpl 源
{$Contacts[0]}<br />
{$Contacts[1]}<br />
{* you can print arrays of arrays as well *}
{$Contacts[2][0]}<br />
{$Contacts[2][1]}<br />
这将输出
555-222-9876<br /> zaphod@slartibartfast.example.com<br /> 555-444-3333<br /> 555-111-1234<br />
PHP 分配的 对象的 属性可以通过指定 -> 符号后的属性名称来引用。
示例 4.5:访问对象属性
name: {$person->name}<br />
email: {$person->email}<br />
这将输出
name: Zaphod Beeblebrox<br /> email: zaphod@slartibartfast.example.com<br />