Skip to content

registerPlugin()

动态注册插件

描述

void

registerPlugin

string

type

string

name

mixed

callback

bool

cacheable

mixed

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(), 插件 函数, 插件块 函数, 插件编译器 函数, 以及 创建插件 修饰符 部分。