myfun.tpl
自定义函数
自定义函数的使用配置
<{*这是注释*}>
<{myfun times="10" con="Hello world, this is user defined function!" color="red" size="5"}>
now time is
<{date_now format="%Y/%m/%d"}>
<{*下面是自定义块函数调用*}>
下面是块标签
<{blockTest times="10" color="green" size="5"}>
Hello world,this is block function test!
<{/blockTest}>
userdefinefunction.php
"' );
$smarty = new Smarty ();
$smarty->left_delimiter = "<{";
$smarty->right_delimiter = "}>";
// 注册plugin函数中的三个参数
// type defines the type of the plugin. Valid values are "function", "block", "compiler" and "modifier".
// name defines the name of the plugin.
// callback defines the PHP callback. it can be either:
$smarty->registerPlugin ( "function", "myfun", "myfun" );
function myfun($args) {
$str = "";
for($i = 0; $i < $args ['times']; $i ++) {
$str .= "" . $args ['con'] . "
";
}
return $str;
}
$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 () );
}
$smarty->registerPlugin ( "block", "blockTest", "blockTest" );
// 自定义函数(块方式)
function blockTest($args, $con) {
$str = "";
// 此处注意为什么要加empty判断,如果不加此判断的话,在$con为空的情况下,$str也会被输出十次,从而造成页面中有很多的空行,这种问题的原因是
// 因为smarty计算在前,你获取数据在后,也就是说第一次时,$con已经被smarty计算过了(虽然$con没有值),但是确实在smarty内部计算过了,而且之后也进行了输出
if (! empty ( $con )) {
for($i = 0; $i < $args ['times']; $i ++) {
$str .= "" . $con . "
";
}
} // echo $str;
return $str;
}
$smarty->display ( "myfun.tpl" );
>