smarty变量--从PHP分配的变量

关联数组

数组下标

对象

 

调用从PHP分配的变量需在前加"$"符号(译注:同php一样)。

 

例 4-2.分配的变量

PHP code:
<?php
$smarty = new Smarty();
$smarty->assign('firstname', 'Doug');
$smarty->assign('lastname', 'Evans');
$smarty->assign('meetingPlace', 'New York');
$smarty->display('index.tpl');
?>

index.tpl source:

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}.

This above would output:
Hello Doug Evans, glad to see you can make it.
<br />
This weeks meeting is in .
This weeks meeting is in New York.

 

[关联数组]

你也可以通过句号“.”后接数组键的方式来引用从php分配的关联数组变量。
 例4.3.访问关联数组变量

index.php:

$smarty = new Smarty;
$smarty->assign('Contacts',
 array('fax' => '555-222-9876',
 'email' => 'zaphod@slartibartfast.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>

OUTPUT:

555-222-9876<br>
zaphod@slartibartfast.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 source:
{$Contacts[0]}<br />
{$Contacts[1]}<br />
{* you can print arrays of arrays as well *}
{$Contacts[2][0]}<br />
{$Contacts[2][1]}<br />

This will output:
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>

OUTPUT:

name: Zaphod Beeblebrox<br>
email: zaphod@slartibartfast.com<br>


posted @ 2012-03-08 11:53  haiwei.sun  阅读(410)  评论(0编辑  收藏  举报
返回顶部