Table of Contents
Smarty有多种类型的变量。
在Smarty中的变量可以直接显示,或者作为 函数, 属性 and 修饰器, 内部条件表达式等的参数。 要显示变量,可以简单地用 定界符 把变量括起来。
Example 4.1. 变量例子
{$Name}
{$product.part_no} <b>{$product.description}</b>
{$Contacts[row].Phone}
<body bgcolor="{#bgcolor#}">
一个简单的检查Smarty变量的方法是打开Smarty的 调试控制台。
赋值的变量以美元符号 ($) 开头。
Example 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.
可以通过点号“.”来使用赋值的数组变量。
Example 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语法一样。
Example 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赋值的对象的属性和方法,可以通过->来使用。
Example 4.5. 使用对象
name: {$person->name}<br />
email: {$person->email}<br />
输出:
name: Zaphod Beeblebrox<br /> email: zaphod@slartibartfast.example.com<br />