Smarty 是什么?
为何使用?
用例与工作流程
语法比较
模板继承
最佳实践
速成课程
Smarty 允许通过模板访问 PHP 对象。
向模板分配/注册对象时,请确保从该模板访问的所有属性和方法仅用于呈现目的。非常容易通过对象注入应用程序逻辑,这会导致难以管理的糟糕设计。请参阅 Smarty 网站的“最佳实践”部分。
有两种访问对象的方法。
第一种方法具有更好的模板语法。它也更安全,因为已注册的对象可以限制为某些方法或属性。但是,已注册的对象无法循环访问或分配给对象数组等。你选择的方法将取决于你的需求,但在可能的情况下,请使用第一种方法来最大程度地减少模板语法。
如果启用了安全性,则无法访问任何私有方法或函数(以“_”开头)。如果存在同名的函数和属性,则使用该方法。
你可以通过将方法和属性按数组形式列为第三个注册参数来限制可以访问的方法和属性。
默认情况下,通过模板传递给对象的参数与自定义函数获取它们的方式相同。关联数组作为第一个参数传递,而 smarty 对象作为第二个参数传递。如果你希望像传统对象参数传递一样逐个参数传递,请将第四个注册参数设置为 FALSE。
可选第五个参数仅在 format 为 TRUE 时有效,且包含应作为块处理的方法列表。这意味着这些方法在模板中具有结束标签({foobar->meth2}...{/foobar->meth2}),并且方法的参数与 block-function-plugins 的参数具有相同的概要:它们获得四个参数 $params、$content、$smarty 和 &$repeat,它们的行为也如同块函数插件。
示例 17.9. 使用注册对象或已分配对象
<?php
// the object
class My_Object {
function meth1($params, $smarty_obj) {
return 'this is my meth1';
}
}
$myobj = new My_Object;
// registering the object (will be by reference)
$smarty->registerObject('foobar',$myobj);
// if we want to restrict access to certain methods or properties, list them
$smarty->registerObject('foobar',$myobj,array('meth1','meth2','prop1'));
// if you want to use the traditional object parameter format, pass a boolean of false
$smarty->registerObject('foobar',$myobj,null,false);
// We can also assign objects. assign_by_ref when possible.
$smarty->assign_by_ref('myobj', $myobj);
$smarty->display('index.tpl');
?>
下面是访问 index.tpl 中对象的方法
{* access our registered object *}
{foobar->meth1 p1='foo' p2=$bar}
{* you can also assign the output *}
{foobar->meth1 p1='foo' p2=$bar assign='output'}
the output was {$output}
{* access our assigned object *}
{$myobj->meth1('foo',$bar)}
另请参见 registerObject() 和 assign()。