標籤: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自訂標籤