修饰器用于在模板中对变量进行格式化、转换、过滤,语法:{$var|modifier:param1:param2}。本质是调用 PHP 函数,第一个参数自动传入变量值,后续参数按冒号分隔传入。
| 修饰器 | 作用 | 示例 | 输出 |
|---|---|---|---|
| capitalize | 首字母大写 | {$name|capitalize} | Simon |
| upper / lower | 大/小写 | {$name|upper} | SIMON |
| escape | HTML/URL/JS 转义 | {$html|escape:'html'} | 安全输出 |
| truncate | 截断并加省略号 | {$long|truncate:20:'...'} | 前20字符... |
| strip | 去除多余空白 | {$text|strip} | 单行紧凑 |
| indent | 缩进 | {$code|indent:4} | 每行前加4空格 |
| replace | 字符串替换 | {$str|replace:'old':'new'} | 替换后字符串 |
| date_format | 时间戳格式化 | {$ts|date_format:'%Y-%m-%d'} | 2024-05-18 |
| number_format | 数字千分位 | {$num|number_format:2:'.':','} | 12,345.67 |
| default | 默认值 | {$var|default:'N/A'} | 变量为空显示N/A |
<?php
// test.php
require 'libs/Smarty.class.php';
$smarty = new Smarty();
$total = 12345;
$smarty->assign('total', $total);
// PHP 端格式化
$formatted = number_format($total);
$smarty->assign('formatted_total', $formatted);
$smarty->display('test1.htm');
<h1>Total is {$total}</h1>
<h1>Formatted Total is {$formatted_total}</h1>
<?php
// test.php 简化版
require 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->assign('total', 12345);
$smarty->display('test2.htm');
<h1>Total is {$total}</h1>
<h1>Formatted Total is {$total|number_format}</h1>
Total is 12345
Formatted Total is 12,345
在 PHP 中注册自定义函数:
<?php
$smarty->registerPlugin('modifier', 'my_upper', 'strtoupper'); // 直接用内置函数
// 或自定义函数
function smarty_modifier_price_format($value, $currency = '¥') {
return $currency . number_format($value, 2);
}
$smarty->registerPlugin('modifier', 'price_format', 'smarty_modifier_price_format');
模板中使用:{$price|price_format:'$'} → $1,234.56
{$name|lower|capitalize|escape:'html'}
// 执行顺序:lower → capitalize → escape
false,模板输出空字符串__toString 或报错,先用 @count 等预处理善用修饰器,让模板既强大又整洁,业务逻辑彻底下沉到 PHP 层。