1.定义TagLib目录和文件 TagLibSmarTop.class.php
2.配置文件
<?php return array( 'APP_AUTOLOAD_PATH'=>'@.TagLib', //TagLib的位置 @.表示当前文件夹下 'TAGLIB_BUILD_IN'=>'Cx,SmarTop' //Cx是thinkphp基础类库的名称必须引用否则volist等标签就无法使用,SmarTop是自己定义的标签名称 ); ?>
3.定义标签
1 class TagLibSmarTop extends TagLib{ 2 protected $tags = array( 3 //nav定义字段 attr 定义属性 close 是否是闭合 4 'nav' => array('attr'=>'limit,order','close'=>1), 5 'child' =>array('attr'=>'limit,order,typeid','close'=>1), 6 'navnav' =>array('attr'=>'limit,order,typeid','close'=>1), 7 ); 8 /** 9 *定义标签 10 *@param $attr array 接受的属性 11 *@param $content string 接受的字符串 12 *@return $str 返回字符串 13 */ 14 public function _nav($attr,$content){ 15 $tag = $this->parseXmlAttr($attr,$content); 16 $Cate = D('cate'); 17 $result =$Cate->sortChildCate($Cate->order($tag['order'])->limit($tag['limit'])->select()); 18 $str = ''; 19 foreach($result as $k=>$v){ 20 //使用str_replace()函数进行对字符串的替换 21 $str .=str_replace(array('[field:id]','[field:typename]'),array($result[$k]['id'],$result[$k]['name']),$content); 22 } 23 return $str; 24 } 25 /** 26 *定义标签 功能待开发只限于2级栏目调用 27 *@param $attr array 接受的属性 28 *@param $content string 接受的字符串 29 *@return $str 返回字符串 30 */ 31 public function _child($attr,$content){ 32 $tag = $this->parseXmlAttr($attr,$content); 33 $Cate = D('cate'); 34 $where = array('pid'=>empty($tag['typeid'])?0:$tag['typeid']); 35 $result =$Cate->where($where)->order($tag['order'])->limit($tag['limit'])->select(); 36 $str = ''; 37 foreach($result as $k=>$v){ 38 //使用str_replace()函数进行对字符串的替换 39 $str .=str_replace(array('[field:id]','[field:name]'),array($v['id'],$v['name']),$content); 40 } 41 return $str; 42 } 43 public function _navnav($attr,$content){ 44 $tag= $this->parseXmlAttr($attr,$content); 45 //使用php代码以字符串的形式返回到模板里面 要以单引号括起来 46 $str ='<?php '; 47 $str .= '$Cate = M("cate");'; 48 $str .= '$_result = cateModel::sortChildCate($Cate->select());'; 49 $str .='foreach($_result as $__CateNav):'; 50 $str .='extract($__CateNav);?>'; //将数组的$.__CateNav[]去掉 51 $str .= $content; 52 $str .= '<?php endforeach?>'; 53 return $str; 54 } 55 }
4.模板使用标签
1 <navnav limit ='20' order='id ASC'> 2 <li class='nav-lv1-li'> 3 <a href="" class='top-cate'>{$name}</a> 4 <ul> 5 <foreach item='value' name="child"> 6 <li><a href="">{$value.name}</a></li> 7 </foreach> 8 </ul> 9 </li> 10 </navnav>
1 <nav limit ='20' order='id ASC'> 2 <li class='nav-lv1-li'> 3 <a href="" class='top-cate'>[field:typename]</a> 4 <ul> 5 <child limit ='20' order='id ASC' typeid="[field:id]"> 6 <li><a href="">[field:name]</a></li> 7 </child> 8 </ul> 9 </li> 10 </nav>