Smarty 函数
Smarty 提供了一系列函数(也称为“函数”)来增强模板的功能。这些函数可以用于生成内容、格式化数据或执行其他任务,使得模板更具动态性和可复用性。
自定义函数
Smarty 允许你定义自定义函数,以便在模板中使用。自定义函数是自定义的、与 Smarty 自带函数不同的功能扩展。
定义自定义函数:
在 PHP 文件中定义自定义函数需要用到 Smarty 中的 registerPlugin 或者 registerFunction 方法,使用方法如下:
Smarty版末小于Smarty 3.1.33。
$smarty->registerPlugin('function', 'functionName', 'functionImplementation');
Smarty版末大于Smarty 3.1.33。
$smarty->registerFunction('functionName', 'functionImplementation');
其中functionName指的是自定义的函数名称,functionImplementation 指的是具体实现的函数名。
自定义函数使用示例:
在PHP中定义并实现函数:
<?php // 在 PHP 文件中 require('./lib/Smarty.class.php'); $smarty = new Smarty; $smarty->template_dir = './templates'; $smarty->compile_dir = './templates/compile'; $smarty->cache_dir = './templates/cache'; // 自定义函数 function sayHello($params) { return "Hello, {$params['name']}!"; } // 注册自定义函数 $smarty->registerPlugin('function', 'hello', 'sayHello'); $smarty->display('index.tpl'); ?>
在模板中调用自定义函数
{hello name="World"}
Smarty内置函数
Smarty 提供了一些内置的函数,这些函数可以在模板中直接调用。以下是一些常用的内置函数:
html_image:生成一个 HTML 图像标签。
{html_image file="images/logo.png" alt="logo"}
html_options:生成 HTML 选项列表。
{html_options values=$options key_value="id" selected=$selected}
html_select_date:生成一个 HTML 日期选择器。
{html_select_date start_year="2020" end_year="2024" field_order="DMY"}
html_select_time:生成一个 HTML 时间选择器。
{html_select_time hour_range="0,23" minute_interval="5"}
数字格式化
<p>{number_format(12.345, 2)}</p>
求数组长度
<p>{count($list)}</p>
Smarty内置修饰符
Smarty 的修饰符用于在输出变量时进行格式化或处理。以下是一些常用的内置修饰符:
capitalize:将字符串的首字母大写。
{$name|capitalize}
escape:对字符串进行 HTML 转义。
{$description|escape}
date_format:格式化日期。
{$date|date_format:"%Y-%m-%d"}
lower:将字符串转换为小写。
{$title|lower}
upper:将字符串转换为大写。
{$title|upper}
将长字符串按指定宽度换行
<p>{$text|wordwrap:20}</p>
截断字符串到指定长度
<p>{$text|truncate:10}</p>
去除字符串的首尾空白字符
<p>{$text|trim}</p>
替换字符串中的指定部分
<p>{$text|replace:"world":"Smarty"}</p>
系统函数
Smarty 的系统函数用于控制模板的缓存和调试功能:
{$smarty.get}:获取 URL 查询参数。
{$smarty.get.param_name}
{$smarty.config}:获取配置文件的值。
{$smarty.config.some_value}
Smarty 的函数和插件系统为模板引擎提供了强大的扩展能力。通过使用内置函数、修饰符、自定义函数和插件,你可以在模板中实现复杂的功能和动态内容,同时保持代码的清晰和可维护。了解并有效利用这些功能,可以显著提高开发效率和模板的灵活性。