myfun.tpl
<span style="font-size:18px;"><title>自定义函数</title>
<h1>自定义函数的使用配置</h1>
<{*这是注释*}>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<hr>
<{myfun times="10" con="Hello world, this is user defined function!" color="red" size="5"}>
<br>
now time is
<{date_now format="%Y/%m/%d"}>
<{*下面是自定义块函数调用*}>
<br>
下面是块标签
<br>
<{blockTest times="10" color="green" size="5"}>
Hello world,this is block function test!
<{/blockTest}></span>
userdefinefunction.php
<span style="font-size:18px;"><?php
require_once './libs/Smarty.class.php';
date_default_timezone_set ( "Asia/Chongqing" );
header ( '<meta http-equiv="content-type" content="text/html;charset=utf-8/>"' );
$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 .= "<font size='" . $args ['size'] . "' color='" . $args ['color'] . "'>" . $args ['con'] . "</font><br>";
}
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 .= "<font size='" . $args ['size'] . "' color='" . $args ['color'] . "'>" . $con . "</font><br>";
}
} // echo $str;
return $str;
}
$smarty->display ( "myfun.tpl" );
?></span>