Chapter 4. 变量
Smarty有多种类型的变量。
在Smarty中的变量可以直接显示,或者作为 函数, 属性 and 修饰器, 内部条件表达式等的参数。 要显示变量,可以简单地用 定界符 把变量括起来。
- {$Name}
- {$product.part_no} <b>{$product.description}</b>
- {$Contacts[row].Phone}
- <body bgcolor="{#bgcolor#}">
说明
一个简单的检查Smarty变量的方法是打开Smarty的调试控制台。
从PHP赋值的变量
赋值的变量以美元符号 ($
) 开头。
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.
数组赋值
可以通过点号“.”来使用赋值的数组变量。
- <?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 />
原文: https://www.smarty.net/docs/zh_CN/language.variables.tpl