> Smarty模板引擎中文在线手册 > Template Functions [模板函数]

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

上一篇:
下一篇: