Smarty的自定义函数包括三部分:模板自定义函数,PHP自定义函数,按插件形式扩展的自定义函数
模板自定义函数
{assign var="name" value="Lee"}
assign函数用于给一个变量赋值。
{counter start=0 skip=2 print=false}
counter 用于输出一个记数过程。
{cycle values="red,blue"}
cycle用于交替轮换一组数据,比如背景色轮替交换。
{debug}
debug是调试工具,可以查看模板的各项信息。
{eval var=$name}
eval可以显示普通变量和配置变量
{fetch file="http://www.baidu.com/"}
fetch可以引入其他文件的源代码
{html_checkboxes options=$cust checked=$id}
html_checkboxes可以批量显示复选框。
{html_image file="http://www.baidu.com/images/logo.jpg"}
html_image可以载入图片。
{html_options options=$cust selected=$id}
html_options表示下拉选项。
{html_radios options=$cust checked=$id}
html_radios表示单选按钮。
{html_select_date}
可以显示日期的下拉列表,参数众多,可以参考手册
{html_select_time}
可以显示时间的下拉列表,参数众多,可以参考手册
{html_table loop=$data}
可以显示表格
{math equation="$x+$y"}
可以在模板中进行计算。
{mailto address="yc60.com@gmail.com"}
电子邮件。
{popup_init src="js/overlib.js"}
{popup text="This link takes you to my page!"}
载入overlib库,js提示框。
{textformat indent=20}
Lee
{/textformat}
文字格式化。
PHP自定义函数
在模板里注册一个函数,并且可以传参,可以使用register_function(‘模板函数名’,’函数名’)。
//注册函数
<?php
$smarty->registerPlugin("function","date_now", "print_current_date");
function print_current_date($params, $smarty)
{
if(empty($params["format"])) {
$format = "%b %e, %Y";
} else {
$format = $params["format"];
}
return strftime($format,time());
}
?>
模板中,这样...
{date_now}
{* 或者运用自己的格式化形式 *}
{date_now format="%Y/%m/%d"}
在模板里注册一个块,并且可以传参,可以使用register_block(‘模板函数名’,’函数名’)。
<?php
// 函数说明
function do_translation ($params, $content, $smarty, &$repeat, $template)
{
if (isset($content)) {
$lang = $params["lang"];
// 对$content进行翻译...
return $translation;
}
}
// 通过smarty注册
$smarty->registerPlugin("block","translate", "do_translation");
?>
模板这样设置:
{translate}Hello, world!{/translate}
按插件形式扩展的自定义函数
1.如 果 是 函 数 插 件 , 文 件 必 须 放 在 插 件 目 录 (plugins) , 文 件 名 必 须 是function.xxx.php,里面的函数名必须是smarty_function_xxx($params,&$smarty)。
2.如果是块插件,文件必须放在插件目录(plugins),文件名必须是block.xxx.php,里面的函数名必须是smarty_block_xxx($params,$content,&$smarty)。
最新评论