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-name

  • An array of the form array($class, $method) with $class being the class name and $method being a method of the class.

  • 大多数情况下cacheablecache_attrs可被省略。 参见缓存能力设置它们的值。


Example 14.39. 注册函数

  1. <?php
  2. $smarty->registerPlugin("function","date_now", "print_current_date");
  3.  
  4. function print_current_date($params, $smarty)
  5. {
  6. if(empty($params["format"])) {
  7. $format = "%b %e, %Y";
  8. } else {
  9. $format = $params["format"];
  10. }
  11. return strftime($format,time());
  12. }
  13. ?>
  14.  

在模板中:

  1. {date_now}
  2.  
  3. {* 或定义时间格式 *}
  4. {date_now format="%Y/%m/%d"}
  5.  


Example 14.40. 注册块函数

  1. <?php
  2. // 函数定义
  3. function do_translation ($params, $content, $smarty, &$repeat, $template)
  4. {
  5. if (isset($content)) {
  6. $lang = $params["lang"];
  7. // 这里可以放置翻译 $content 的代码
  8. return $translation;
  9. }
  10. }
  11.  
  12. // 注册到Smarty
  13. $smarty->registerPlugin("block","translate", "do_translation");
  14. ?>
  15.  

模板中:

  1. {translate lang="br"}Hello, world!{/translate}
  2.  


Example 14.41. 注册修饰器

  1. <?php
  2.  
  3. // 我们将PHP的stripslashes函数映射成一个Smarty的修饰器
  4. $smarty->registerPlugin("modifier","ss", "stripslashes");
  5.  
  6. ?>
  7.  

模板中可使用ss来过滤反斜线。

  1. <?php
  2. {$var|ss}
  3. ?>
  4.  

参见unregisterPlugin(),插件函数,块函数,编译函数,和 修饰器

原文: https://www.smarty.net/docs/zh_CN/api.register.plugin.tpl