Template Functions 模板函数

本文介绍了Smarty模板引擎中如何创建带有输出及无输出的模板函数。包括如何通过参数数组处理输入值,函数返回值如何在模板中展示,以及如何利用$smarty对象进行变量赋值等关键操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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);
}
?>

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值