Name
registerPlugin() — 注册插件
说明
void registerPlugin(string type,
string name,
mixed callback,
bool cacheable,
mixed cache_attrs);该函数将以插件的形式来注册函数或者方法。 参数如下:
typedefines the type of the plugin. Valid values are "function", "block", "compiler" and "modifier".namedefines the name of the plugin.-
callbackdefines the PHP callback. it can be either:A string containing the function
nameAn array of the form
array(&$object, $method)with&$objectbeing a reference to an object and$methodbeing a string containing the method-nameAn array of the form
array($class, $method)with$classbeing the class name and$methodbeing a method of the class.
大多数情况下
cacheable和cache_attrs可被省略。 参见缓存能力设置它们的值。
Example 14.39. 注册函数
<?php
$smarty->registerPlugin("function","date_now", "print_current_date");
function print_current_date($params, $smarty)
{
if(empty($params["format"])) {
$format = "%b %e, %Y";
} else {
$format = $params["format"];
}
return strftime($format,time());
}
?>
在模板中:
{date_now}
{* 或定义时间格式 *}
{date_now format="%Y/%m/%d"}
Example 14.40. 注册块函数
<?php
// 函数定义
function do_translation ($params, $content, $smarty, &$repeat, $template)
{
if (isset($content)) {
$lang = $params["lang"];
// 这里可以放置翻译 $content 的代码
return $translation;
}
}
// 注册到Smarty
$smarty->registerPlugin("block","translate", "do_translation");
?>
模板中:
{translate lang="br"}Hello, world!{/translate}
Example 14.41. 注册修饰器
<?php
// 我们将PHP的stripslashes函数映射成一个Smarty的修饰器
$smarty->registerPlugin("modifier","ss", "stripslashes");
?>
模板中可使用ss来过滤反斜线。
<?php
{$var|ss}
?>
参见
unregisterPlugin(),
插件函数,
块函数,
编译函数,
和
修饰器。