第四章 变量

目录
PHP中赋值的变量
从配置文件中调入的变量
{$smarty}保留变量

    Smarty有几种不同类型的变量。变量类型取决于它的前缀字符或者它由什么字符对包含。

    Smarty中的变量可以直接显示也可以用作函数属性以及修饰符的参数,用于条件判断表达式等等。要打印一个变量,只要将它放在分隔符之间,并且是分隔符中唯一的内容。

Example 4-1. Example variables

{$Name}

{$product.part_no} <b>{$product.description}</b>

{$Contacts[row].Phone}

<body bgcolor="{#bgcolor#}">

特别提示:检查Smarty变量的简单方法是通过调试终端

PHP中赋值的变量

    在PHP中赋值的变量的引用是在之前以$开始(类似PHP)。在模板中通过{assign}函数赋值的变量也用这样的方法显示。

例子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 weeks meeting is in {$meetingplace}.
{* 下行可以 *}
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中赋值的关联数组变量。

例子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 />