Modifiers 修正器

优质
小牛编辑
132浏览
2023-12-01

Modifiers are little functions that are applied to a variable in the template before it is displayed or used in some other context. Modifiers can be chained together.
修正器是一些短小的函数,这些函数被应用于模版中的一个变量,然后变量再显示或用于其他的一些文档。我们可以把修正器链接起来。

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

The first parameter to the modifier plugin is the value on which the modifier is supposed to operate. The rest of the parameters can be optional, depending on what kind of operation is supposed to be performed.
修正器插件的第一个参数是不可缺少的。剩余的参数是可选的,它们的有无取决于期望执行哪一种操作。

The modifier has to return the result of its processing.
修正器必须有返回值。

See also register_modifier(), unregister_modifier().
也可参考register_modifier(), unregister_modifier().

Example 16-3. simple modifier plugin简单修正器插件

This plugin basically aliases one of the built-in PHP functions. It does not have any additional parameters.
这个插件主要目的是用另一个名字替换一个内置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);
}
?>

Example 16-4. more complex modifier plugin更加复杂的修正器插件

<?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($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;
}
?>