修饰符

    修饰符是这样一类小函数,在模板变量显示或用作它途之前作用于其上。修饰符可以串联在一起。

mixed smarty_modifier_name (mixed $value, [mixed $param1, ...])

    传递给修饰符的第一个参数是修饰符将要进行操作的值。其它的参数是可选的,取决于要执行的是怎样的的操作。

    修饰符必须返回其处理的结果。

例子16-3. 简单的修饰符插件

    该插件只是重复了内建PHP函数的功能。它没有额外的参数。

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     modifier.capitalize.php
 * Type:     modifier
 * Name:     capitalize
 * Purpose:  capitalize words in the string
 * -------------------------------------------------------------
 */
function smarty_modifier_capitalize($string)
{
    return 
ucwords($string);
}
?>

例子16-4. 较为复杂的修饰符插件

<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     modifier.truncate.php
 * Type:     modifier
 * Name:     truncate
 * Purpose:  Truncate a string to a certain length if necessary,
 *           optionally splitting in the middle of a word, and
 *           appending the $etc string.
 * -------------------------------------------------------------
 */
function smarty_modifier_truncate($string$length 80$etc '...',
                                  
$break_words false)
{
    if (
$length == 0)
        return 
'';

    if (
strlen($string) > $length) {
        
$length -= strlen($etc);
        
$fragment substr($string0$length+1);
        if (
$break_words)
            
$fragment substr($fragment0, -1);
        else
            
$fragment preg_replace('/\s+(\S+)?$/'''$fragment);
        return 
$fragment.$etc;
    } else
        return 
$string;
}
?>

    参见register_modifier()unregister_modifier()