thinkphp的默认标签解析器在Lib/Template/TagLib/TagLibCx.class中
里面定义了常用的volist php 等常用thinkphp的标签
这里笔者在这个类中添加一个<category>的标签解析
标签格式:
<category parentid='0' ><{$cat.catname}></category>
标签作用:
循环输出父类id是parentid的栏目
1.在tagLibCx.class 的私有属性中添加
'category'=array('attr'=>'parentid',level=>3)
其中attr:标签的属性 level标签的嵌套层次
2.添加解析函数
标签的解析原理就是通过读取xml文件得到相应的信息,然后再拼凑成所需要的
php源代码,最后通过echo 在页面上输出
具体代码如下:
public function _category($attr,$content){//把标签的所有属性解析到$tag数组里面$tag = $this->parseXmlAttr($attr,'category'); //得到标签里面的属性$parentid= $tag['parentid']; //定义页面解析的变量$result = !empty($tag['result'])?$tag['result']:'cat'; //定义数据查询的结果存放变量$key = !empty($tag['key'])?$tag['key']:'i';$mod = isset($tag['mod'])?$tag['mod']:'2'; //拼凑数据库查询语句 这里直接用了CategoryModel封装好的函数$sql = "D('Category')->";$sql .= "getCategorys(".$parentid.')'; //拼凑输出字符$parsestr = '<?php $_result='.$sql.'; if ($_result): $'.$key.'=0;';$parsestr .= 'foreach($_result as $key=>$'.$result.'):';$parsestr .= '++$'.$key.';$mod = ($'.$key.' % '.$mod.' );?>';$parsestr .= $content;//解析在category标签中的内容$parsestr .= '<?php endforeach; endif;?>';return $parsestr; } CategoryModel中的getCategorys方法/** 根据parentid得到栏目信息* $parentid 父id* $withSelf 是否包含自己*/ public function getCategorys($parentid,$withSelf=0){$parentid=intval($parentid);$categorys=$this->where(array('parentid'=>$parentid,'ismenu'=>1))->order('listorder ASC')->select();//包含自己if($withSelf){$categorys2=$this->where(array('id'=>$parentid,'ismenu'=>1))->limit(1)->select();$category=array_merge($categorys,$categorys2);}return $categorys; }3.页面上的引用<category parentid='0'><{$cat.catname}></category>这样一个标签就做好了 ^_^!就可以甩掉那个volist在页面上动态输出我们想要的东西了
到此这篇关于ThinkPHP的标签制作实例讲解的文章就介绍到这了,更多相关ThinkPHP的标签制作内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!