跳到内容

从 PHP 分配的变量

在 PHP 中分配的变量在引用前添加美元符号 ($)。

示例

<?php
use Smarty\Smarty;
$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.

关联数组

您还可以通过在点“.”符号后指定键来引用关联数组变量。

<?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 语法非常类似。

<?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 分配的 对象的 属性。

name:  {$person->name}<br />
email: {$person->email}<br />

这将输出

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