更新时间:2022-09-01 17:04:15
研究ThinkPHP自定义标签的时候,发现网上很多教程都很乱,官网又没有给出比较详细的方法,所以就自己研究了一下,现在将ThinkPHP的方法详细的记录下来。
1.建立TP的项目,略过
2.在config.php中加入'APP_AUTOLOAD_PATH'=>'@.TagLib',自动加载TagLib里面的文件
3.在项目名称/Lib中建立TagLib文件夹
4.在TagLib文件夹中新建一个TagLibXl.class.php文件(格式:TagLib自定义的名称,首字母大写)
5.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<?php import( 'TagLib' );
class TagLibXl extends TagLib{
protected $tags = array (
'list' => array (
'attr' => 'table,limit' , //设置标签属性
'level' => '3' , //循环次数
'close' => '1' , //是否闭合
),
);
function _list( $attr , $content ){
$tag = $this ->parseXmlAttr( $attr , 'list' ); //解析操作,TP的自定义标签是基于xml的
$db =M( $tag [ 'table' ]); //根据返回的table值实例化
$list = $db ->limit( $tag [ 'limit' ])->select(); //查询返回数据
preg_match_all( "/\[field\:\w*\]/" , $content , $match ); //获取返回值里[field:xxx]这种格式
$match = $match [0];
$match = array_unique ( $match ); //去掉数组重复项
foreach ( $match as $i => $vo ){
$field [ $i ]= substr ( $vo ,7, count ( $vo )-2);
}
//以下循环为遍历将[field:xxx]格式替换为实际内容
foreach ( $list as $i => $value ){
if ( $i ==0){
$parseStr = $content ;
} else {
$parseStr = $parseStr . $content ;
}
foreach ( $match as $j => $vo ){
$parseStr = str_replace ( $vo , $value [ $field [ $j ]], $parseStr );
}
}
//解析内容模板,并返回字符串
if (! empty ( $parseStr )) {
return $this ->tpl->parse( $parseStr );
}
return ;
}
} |
在模板中使用方法:
1
2
3
4
5
6
|
< taglib name = "xl" />
< ul >
< xl:list table = "Article" limit = "0,3" >
< li >< span >[field:id]</ span >< a href = "" >[field:title]</ a ></ li >
</ xl:list >
</ ul >
|