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

修饰器

修饰器是一些小函数, 它们会对模板中的变量,在显示之前或使用前进行处理。 修饰器可以连用。

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

第一个参数是修饰器所修饰的变量值。 余下的参数是可选的,它们是附加传递给修饰器的参数。

修饰器必须return处理的结果。

Example 18.3. 一个简单的修饰器

这个修饰器简单地用别名替代了PHP内置的函数,不带其他的附加参数。


<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     modifier.capitalize.php
 * Type:     modifier
 * Name:     capitalize
 * Purpose:  让文字首字母大写
 * -------------------------------------------------------------
 */
function smarty_modifier_capitalize($string)
{
    return ucwords($string);
}
?>


Example 18.4. 更复杂的修饰器


<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     modifier.truncate.php
 * Type:     modifier
 * Name:     truncate
 * Purpose:  截取字符串长度,多余的部分会被$etc字符串代替。
 * -------------------------------------------------------------
 */
function smarty_modifier_truncate($string, $length = 80, $etc = '...',
                                  $break_words = false)
{
    if ($length == 0)
        return '';

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

     

参见: registerPlugin(), unregisterPlugin().

Comments
No comments for this page.

Advertisement