Get Smarty

Donate

Smarty Icon

You may use the Smarty logo according to the trademark notice.

Smarty Template Engine Smarty Template Engine

For sponsorship, advertising, news or other inquiries, contact us at:

Sites Using Smarty

Buy cheap glasses from Cheapglasses123.com and save up to 80%.

Where to buy prescription glasses? EyewearCanada.com is your best choice!

Advertisement

模板函数

void smarty_function_name( $params,  
  $template);  
array $params;
object $template;
 

模板传递到函数的参数变量, 都包含在$params数组内。

函数输出(返回值)的内容将替代函数标签调用的位置, 如{fetch}函数。 同时,函数也可以仅执行一些任务而没有输出,如 {assign}函数。

如果函数中对模板赋值,或使用其他Smarty提供的功能, 可以通过 $template对象来进行, 例如$template->foo()

Example 18.1. 带输出的函数插件


<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.eightball.php
 * Type:     function
 * Name:     eightball
 * Purpose:  输出一个随机的答案
 * -------------------------------------------------------------
 */
function smarty_function_eightball($params, Smarty_Internal_Template $template)
{
    $answers = array('Yes',
                     'No',
                     'No way',
                     'Outlook not so good',
                     'Ask again soon',
                     'Maybe in your reality');

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


模板中:

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

Example 18.2. 不带输出的函数插件


<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.assign.php
 * Type:     function
 * Name:     assign
 * Purpose:  赋值一个变量到模板
 * -------------------------------------------------------------
 */
function smarty_function_assign($params, Smarty_Internal_Template $template)
{
    if (empty($params['var'])) {
        trigger_error("assign: missing 'var' parameter");
        return;
    }

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

    $template->assign($params['var'], $params['value']);     
    
}
?>

      


参见: registerPlugin(), unregisterPlugin().

Comments
No comments for this page.

Advertisement