ThinkPHP Label Making Tutorial

  • 2021-07-07 06:43:32
  • OfStack

This article explains the ThinkPHP label production method with examples, for ThinkPHP beginners or developers have a certain reference value.

Generally speaking, the default tag parser for ThinkPHP is in Lib/Template/TagLib/TagLibCx. class (version 2.1 is in ThinkPHP/Lib/Think/Template/TagLib/TagLibCx. class. php), which defines commonly used ThinkPHP tags such as volist php

Here we will add 1 to this class < category > Gets or sets the label resolution of.

1. Label format:


<category parentid='0' ><{$cat.catname}></category>

2. Label function:

The loop output parent class id is the column of parentid

3. Operation steps:

1. In the private properties of tagLibCx. class, add:


'category'=array('attr'=>'parentid',level=>3)

Where attr: The attribute of the tag level the nesting level of the tag

2. Add parsing functions

The parsing principle of tag is to get the corresponding information by reading xml file, then piece together the required php source code, and finally output it on the page through echo.

The specific code is as follows:


public function _category($attr,$content)
{
// Resolves all attributes of the tag to $tag Inside the array 
$tag = $this->parseXmlAttr($attr,'category');
// Get the attributes inside the tag 
$parentid= $tag['parentid'];
// Define variables for page resolution 
$result = !empty($tag['result'])?$tag['result']:'cat'; // Define the result storage variable of data query 
$key = !empty($tag['key'])?$tag['key']:'i';
$mod = isset($tag['mod'])?$tag['mod']:'2';
// Piece together database query statements   It is used directly here CategoryModel Encapsulated function 
$sql = "D('Category')->";
$sql .= "getCategorys(".$parentid.')';
// Piece together output characters 
$parsestr = '<?php $_result='.$sql.'; if ($_result): $'.$key.'=0;';
$parsestr .= 'foreach($_result as $key=>$'.$result.'):';
$parsestr .= '++$'.$key.';$mod = ($'.$key.' % '.$mod.' );?>';
$parsestr .= $content;// Parsing in category Contents in the tag 
$parsestr .= '<?php endforeach; endif;?>';
return $parsestr;
}

getCategorys method in CategoryModel:


/*
*  According to parentid Get column information 
* $parentid  Father id
* $withSelf  Do you include yourself 
*/
public function getCategorys($parentid,$withSelf=0)
{
$parentid=intval($parentid);
$categorys=$this->where(array('parentid'=>$parentid,'ismenu'=>1))->order('listorder ASC')->select();
// Include oneself 
if($withSelf)
{
$categorys2=$this->where(array('id'=>$parentid,'ismenu'=>1))->limit(1)->select();
$category=array_merge($categorys,$categorys2);
}
return $categorys;
}

3. References on the page:


<category parentid='0'>
<{$cat.catname}>
</category>

In this way, a label is ready! ! You can get rid of that volist and dynamically output what we want on the page!


Related articles: