smarty中自定义函数的使用(包括块方式)

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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值