Template Functions
模板函数

void smarty_function_name(array $params, object &$smarty)

All attributes passed to template functions from the template are contained in the $params as an associative array. Either access those values directly, e.g. $params['start'] or use extract($params) to import them into the symbol table.

模板传递给模板函数的所有的属性都包含在参数数组 $params 中,既可以通过如: $params['start'] 的方式直接处理其中的值,也可以使用 extract($params) 的方式将所有值导入符号表中。

The output (return value) of the function will be substituted in place of the function tag in the template (fetch() function, for example). Alternatively, the function can simply perform some other task without any output (assign() function).

函数输出(返回值)的内容将取代模板中函数名称出现的位置(例如:fetch()函数)。同时函数也可能只是执行些后台任务,并无任何输出

If the function needs to assign some variables to the template or use some other Smarty-provided functionality, it can use the supplied $smarty object to do so.

如果函数需要向模板中增加变量或者使用Smarty提供的某些功能,可以通过 $smarty 对象实现。

See also相关内容: register_function(), unregister_function().

Example 16-1. function plugin with output
例16-1:有输出插件函数

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.eightball.php
 * Type:     function
 * Name:     eightball
 * Purpose:  outputs a random magic answer
 * -------------------------------------------------------------
 */
function smarty_function_eightball($params, &$smarty)
{
    $answers = array('Yes',
                     'No',
                     'No way',
                     'Outlook not so good',
                     'Ask again soon',
                     'Maybe in your reality');

    $result = array_rand($answers);
    return $answers[$result];
}
?>

which can be used in the template as:

在模板中调用方法如下:

Question: Will we ever have time travel?
Answer: {eightball}.

Example 16-2. function plugin without output
例16-2:无输出插件函数

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.assign.php
 * Type:     function
 * Name:     assign
 * Purpose:  assign a value to a template variable
 * -------------------------------------------------------------
 */
function smarty_function_assign($params, &$smarty)
{
    extract($params);

    if (empty($var)) {
        $smarty->trigger_error("assign: missing 'var' parameter");
        return;
    }

    if (!in_array('value', array_keys($params))) {
        $smarty->trigger_error("assign: missing 'value' parameter");
        return;
    }

    $smarty->assign($var, $value);
}
?>