ThinkPHP自訂標籤

來源:互聯網
上載者:User

標籤:xtend   common   迴圈   位置   組合   return   bsp   extract   ace   

自訂標籤的之前,先看看Think PHP自己是如何自訂標籤的:

具體位置:ThinkPHP / Library / Think / Template / TagLib / Cx.class.php

可以看一個 foreach 標籤是如何寫的:

<?phpnamespace Think\Template\TagLib;use Think\Template\TagLib;/** * CX標籤庫解析類 */class Cx extends TagLib {    // 標籤定義    protected $tags   =  array(        // 標籤定義: attr 屬性列表 close 是否閉合(0 或者1 預設1) alias 標籤別名 level 嵌套層次                ‘foreach‘   =>  array(‘attr‘=>‘name,item,key‘,‘level‘=>3)    );    /**     * foreach標籤解析 迴圈輸出資料集     */    public function _foreach($tag,$content) {        $name       =   $tag[‘name‘];        $item       =   $tag[‘item‘];        $key        =   !empty($tag[‘key‘])?$tag[‘key‘]:‘key‘;        $name       =   $this->autoBuildVar($name);        $parseStr   =   ‘<?php if(is_array(‘.$name.‘)): foreach(‘.$name.‘ as $‘.$key.‘=>$‘.$item.‘): ?>‘;        $parseStr  .=   $this->tpl->parse($content);        $parseStr  .=   ‘<?php endforeach; endif; ?>‘;        if(!empty($parseStr)) {            return $parseStr;        }        return ;    }}

 

下面說下自訂標籤:

 

第一步:修改:修改Application/Common/conf/config.php

增加如下一條配置;
‘TAGLIB_BUILD_IN‘ => ‘Cx,Common\Tag\My‘, //載入自訂標籤

<?phpreturn array (  ‘TAGLIB_BUILD_IN‘ => ‘Cx,Common\\Tag\\My‘,);?>

cx是內建的標籤庫,Common\Tag\My是自訂的標籤庫位置;

樣本是在Application/Common/Tag目錄下建的My.class.php

 

第二步:

建立My.class.php檔案

命名空間要和配置項中填寫的一致;如;

<?phpnamespace Common\Tag;use Think\Template\TagLib;class My extends TagLib{    };

 

標籤分為兩種:

閉合標籤就是單標籤;比如a標籤、img標籤等等;

非閉合標籤就是對標籤;比如div、p標籤等等;

我寫的標籤:

<?phpnamespace Common\Tag;use Think\Template\TagLib;class My extends TagLib{    // 定義標籤    protected $tags = array(        ‘topcates‘=> array(‘attr‘=>‘limit‘)    );    public function _topcates($attr,$content){        //調用父類        $limit = isset($attr[‘limit‘]) ? $attr[‘limit‘] : ‘‘;        // 組合PHP代碼的字串        $str = ‘<?php ‘;        $str .= ‘$where = array("pid" =>0);‘;        $str .= ‘$_topcatesResult = M("category")->where($where)->limit(‘.$limit.‘)->select();‘;        $str .= ‘foreach($_topcatesResult as $v):‘;        $str .= ‘extract($v);?>‘;        $str .= $content;        $str .= ‘<?php endforeach;?>‘;        return $str;    }};

標籤調用:

<topcates limit=‘3‘><li><a href="{:U(‘List/index‘,array(‘id‘=>$id))}">{$name}</a></li></topcates>

 

ThinkPHP自訂標籤

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.