This article explained the thinkphp label's making method by the example, for the thinkphp beginner or the development personnel All has certain reference value.
In general, the default label parser for thinkphp is in Lib/template/taglib/taglibcx.class (version 2.1 is located in thinkphp/lib/think/template/taglib/ TagLibCx.class.php), which defines commonly used thinkphp tags such as volist php
Here we add a <category> tag resolution to this class.
first, the label format:
<category parentid= ' 0 ' ><{$cat .catname}></category>
Second, the role of the label:
Loop output parent class ID is parentid column
Third, the operation steps:
1. Add to the private property of Taglibcx.class:
' Category ' =array (' attr ' => ' ParentID ', level=>3)
Where attr: The nesting level of the label's attribute levels label
2. Add an analytic function
The parsing principle of the tag is to get the corresponding information by reading the XML file, then piecing together the required PHP source code, and finally outputting the page via Echo.
The specific code is as follows:
Public Function _category ($attr, $content)
{
//parse all attributes of the label into $tag array
$tag = $this->parsexmlattr ($attr, ' category ');
Get the attributes inside the tag
$parentid = $tag [' ParentID '];
Define a variable for page resolution
$result =!empty ($tag [' result ']) $tag [' Results ']: ' cat ';//define the result of the data query to hold the variable
$key =!empty ($tag [' key '] ] $tag [' key ']: ' I ';
$mod = Isset ($tag [' mod ']) $tag [' MoD ']: ' 2 ';
Piecing together the database query statement here directly with the Categorymodel encapsulated function
$sql = "D (' Category ')->";
$sql. = "Getcategorys (". $parentid. ') ';
Patchwork output character
$parsestr = ' <?php $_result= '. $sql. '; if ($_result): $ '. $key. ' =0; ';
$parsestr. = ' foreach ($_result as $key =>$ '. $result '): ';
$parsestr. = ' ++$ '. $key '; $mod = ($ '. $key. '% '. $mod. ') > ';
$parsestr. = $content;//resolve content in the category label
$parsestr. = ' <?php Endforeach endif;? > ';
return $parsestr;
}
The Getcategorys method in Categorymodel:
* * According to parentid get column information
* $parentid Parent ID
* $withSelf whether it contains its own *
/public
function Getcategorys ($ ParentID, $withSelf =0)
{
$parentid =intval ($parentid);
$categorys = $this->where (Array (' ParentID ' => $parentid, ' Ismenu ' =>1))->order (' Listorder ASC ')-> Select ();
Contains itself
if ($withSelf)
{
$categorys 2= $this->where (array (' ID ' => $parentid, ' Ismenu ' =>1))- >limit (1)->select ();
$category =array_merge ($categorys, $categorys 2);
}
return $categorys;
}
3. References on the page:
<category parentid= ' 0 ' >
<{$cat .catname}>
</category>
Such a label is done!! You can get rid of that volist. Dynamically outputting what we want on the page!