什么是 Smarty?
为什么使用它?
用例和工作流程
语法比较
模板继承
最佳实践
速成教程
修饰符是在模板中将它们显示或用于其它上下文之前,应用于可变的小函数。修饰符可以串联使用。
mixed smarty_modifier_name( |
$value, | |
$param1); |
mixed $value;[mixed $param1, ...];修饰符插件的第一个参数是在其上操作修饰符的值。其它参数是可选的,具体取决于要执行何种操作类型。
修饰符必须返回其处理的结果。
示例 18.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);
}
?>
示例 18.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($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;
}
?>