变量赋值
一旦你学会了如何使用变量,模板便会开始变得非常有用。
基本分配
让我们重新审视基础部分中的示例。以下脚本将一个值分配给“companyName”变量并渲染模板
<?php
use Smarty\Smarty;
$smarty = new Smarty();
$smarty->assign('companyName', 'AC & ME Corp.');
$smarty->display('footer.tpl');
footer.tpl
Smarty 将对分配给变量 companyName
的值应用 escape 修饰符 并将 {$companyName|escape}
替换为结果。
使用 $smarty->assign()
是将数据分配给模板的最常见方式,但还有其他几种方法。
将数据附加到现有变量
使用 append()
,您可以将数据添加到现有变量中,通常是数组。
如果您追加到字符串值,它将被转换为数组值然后附加到该值。您可以显式地传递 name/value 对,或包含 name/value 对的关联数组。如果您传递第三个可选参数 TRUE,则值将与当前数组合并,而不是附加。
示例
<?php
// This is effectively the same as assign()
$smarty->append('foo', 'Fred');
// After this line, foo will now be seen as an array in the template
$smarty->append('foo', 'Albert');
$array = [1 => 'one', 2 => 'two'];
$smarty->append('X', $array);
$array2 = [3 => 'three', 4 => 'four'];
// The following line will add a second element to the X array
$smarty->append('X', $array2);
// passing an associative array
$smarty->append(['city' => 'Lincoln', 'state' => 'Nebraska']);
分配给模板对象
当您使用模板对象时,如在渲染模板中所述,您可以直接将数据分配给模板对象,而不是分配给 Smarty。通过这种方式,您可以为不同的模板使用不同的数据集。
例如
<?php
use Smarty\Smarty;
$smarty = new Smarty();
$tplBlue = $smarty->createTemplate('blue.tpl');
$tplBlue->assign('name', 'The one');
$tplBlue->display();
$tplRed = $smarty->createTemplate('red.tpl');
$tplRed->assign('name', 'Neo');
$tplRed->display();
使用数据对象
对于更为复杂的用例,Smarty 支持数据对象的概念。数据对象是用来存储数据的容器。在创建模板时,数据对象可以附加到模板中。这允许对数据进行细粒度的重用。
例如
<?php
use Smarty\Smarty;
$smarty = new Smarty;
// create a data object
$data = $smarty->createData();
// assign variable to the data object
$data->assign('name', 'Neo');
// create template object which will use variables from the data object
$tpl = $smarty->createTemplate('index.tpl', $data);
// display the template
$tpl->display();
清除分配的数据
在重用模板时,可能需要清除先前运行中分配的数据。使用 clearAllAssign()
可清除数据对象、模板对象或 Smarty 对象中所有已分配变量的值。
示例
<?php
// assigning data to the Smarty object
$smarty->assign('Name', 'Fred');
// ...
$smarty->clearAllAssign();
// using a data object
$data = $smarty->createData();
$data->assign('name', 'Neo');
// ...
$data->clearAllAssign();
// using a template
$tplBlue = $smarty->createTemplate('blue.tpl');
$tplBlue->assign('name', 'The one');
// ...
$tplBlue->clearAllAssign();
请注意,仅在以下情况下清除已分配的数据才会有用:
- 重复利用模板,以及
- 在每次重复中使用的变量可能会改变
如果脚本仅运行一次,然后结束,或者你始终分配相同的变量,清除分配的数据则无效。