Name
registerPlugin() — 注册插件
说明
void registerPlugin(string type,
string name,
mixed callback,
bool cacheable,
mixed cache_attrs);
该函数将以插件的形式来注册函数或者方法。 参数如下:
type
defines the type of the plugin. Valid values are "function", "block", "compiler" and "modifier".name
defines the name of the plugin.callback
defines the PHP callback. it can be either:
A string containing the function
name
An array of the form
array(&$object, $method)
with&$object
being a reference to an object and$method
being a string containing the method-nameAn array of the form
array($class, $method)
with$class
being the class name and$method
being a method of the class.
- 大多数情况下
cacheable
和cache_attrs
可被省略。 参见缓存能力设置它们的值。
- <?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"}
- <?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}
- <?php
- // 我们将PHP的stripslashes函数映射成一个Smarty的修饰器
- $smarty->registerPlugin("modifier","ss", "stripslashes");
- ?>
模板中可使用ss
来过滤反斜线。
- <?php
- {$var|ss}
- ?>
参见unregisterPlugin()
,插件函数,块函数,编译函数,和 修饰器。
原文: https://www.smarty.net/docs/zh_CN/api.register.plugin.tpl