ThinkPHP標籤製作教程_php執行個體

來源:互聯網
上載者:User
本文以執行個體講解了ThinkPHP標籤的製作方法,對於ThinkPHP的初學者或者開發人員都有一定的借鑒價值。

一般來說,ThinkPHP的預設標籤解析器在Lib/Template/TagLib/TagLibCx.class(2.1版本位於ThinkPHP/Lib/Think/Template/TagLib/TagLibCx.class.php)中,裡面定義了常用的如volist php 等常用ThinkPHP的標籤

這裡我們就在這個類中添加一個的標籤解析。

一、標籤格式:

<{$cat.catname}>

二、標籤作用:

迴圈輸出父類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.頁面上的引用:

<{$cat.catname}>

這樣一個標籤就做好了!!就可以甩掉那個volist在頁面上動態輸出我們想要的東西了!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.