Instance of Custom Tag Library under ThinkPHP Grouping
- 2021-07-24 10:29:42
- OfStack
This paper describes the implementation method of custom tag library under ThinkPHP grouping. Share it for your reference. The details are as follows:
The custom tag library should be located in the ThinkPHP\\ Extend\\ Driver\\ TagLib directory
1 The new tag class library file name is TagLibBlog. class. php.
2 Edit the newly created class library file just now, create a new class, and inherit the parent class of TagLib
import('TagLib');
class TagLibBlog extends TagLib {
}
3 Declare 1 protected member variable $tags in the class
class TagLibBlog extends TagLib {
protected $tags =array(
'mynav'=>array('attr'=>'limit,order','close'=>1)
/* www.ofstack.com
Here $tags Within an array , Every unit is also every 1 Bank representative 1 Tags , For example {dede:article}, We also define it here 1 A mynav,
And then every 1 The key name of the row label is the label name , The key value is 1 Array of numbers , The array contains two cells , No. 1 1 One is attr Is the attribute in the tag , Separated by commas ,
Such as num,typeid Wait ,close If the value of is 0 It is a non-closed label ,1 The word is closed, which means to use </mynav> To end
*/
);
}
After defining the label, we need to realize the function of the label. Here, we declare a function directly under the class file, which starts with _ and ends with the label name mynav
public function _mynav($attr,$content){
$attr=$this->parseXmlAttr($attr);
import('@.Class.Tool');
$categories=M('category')->limit($attr['limit'])->order($attr['order'])->select();
$categories=Tool::formatMultiArray($categories);
$str='';
for($i=0;$i<count($categories);$i++){
$model=array(
'/[field.id]/',
'/[field.name]/'
);
$replace=array(
$categories[$i]['id'],
$categories[$i]['name']
);
$str.=preg_replace($model,$replace,$content);
}
return $str;
}
After defining the label, you need to load the tag library in the project public configuration file
config.php
// Load Tag Library
'APP_AUTOLOAD_PATH'=>'@.TagLib',
'TAGLIB_BUILD_IN'=>'Cx,Blog',
The complete source code of tag library is as follows:
<?php
import('TagLib');
class TagLibBlog extends TagLib {
protected $tags=array(
'mynav'=>array('attr'=>'limit,order','close'=>1)
);
public function _mynav($attr,$content){
$attr=$this->parseXmlAttr($attr);
import('@.Class.Tool');
$categories=M('category')->limit($attr['limit'])->order($attr['order'])->select();
$categories=Tool::formatMultiArray($categories);
$str='';
for($i=0;$i<count($categories);$i++){
$model=array(
'/[field.id]/',
'/[field.name]/'
);
$replace=array(
$categories[$i]['id'],
$categories[$i]['name']
);
$str.=preg_replace($model,$replace,$content);
}
return $str;
}
}
?>
Tests in templates:
<mynav limit="0,10" order="sort asc">
<a href="[field.id]">[field.name]</a><br/>
</mynav>
I hope this article is helpful to everyone's ThinkPHP framework programming.