1配置标签:
在配置文件中加入
'TAGLIB_BUILD_IN' => 'cx,webshop', // webshop 为自定义标签类名称
2编写自定义标签类:
在thinkphp3.2 TagLib目录加入Webshop类,本自定义标签模仿tpshop,该类代码如下namespace Think\Template\TagLib;
use Think\Template\TagLib;
/**
* 自定义标签
*/
class Webshop extends TagLib {
protected $tags = array(
'adv' => array('attr'=>'limit,order,where,item,type','close'=>1),
);
/**
* 广告标签
* @access public
* @param array $tag 标签属性
* @param string $content 标签内容
* @return string
*/
public function _adv($tag,$content){
$order = $tag['order']; //排序
$type = $tag['type']; //显示方式
//type 0轮播,1单张,2多张
switch(intval($type)){
case 0: $limit = '';break;
case 1: $limit = '1';break;
case 2: $limit = $tag['limit'];break;
default:
$limit = '1';break;
}
$where = $tag['where']; //查询条件
$item = !empty($tag['item']) ? $tag['item'] : 'item';// 返回的变量item
$key = !empty($tag['key']) ? $tag['key'] : 'key';// 返回的变量key
$pid = !empty($tag['pid']) ? $tag['pid'] : '0';// 返回的变量key
$str = '<?php ';
$str .= '$pid ='.$pid.';';
$str .= '$result = M("banner")->field("bn.id,media_type,ad_name,ad_link,ad_code,link_man,link_email,link_phone,click_count,target,bgcolor,is_wap,ad_width,ad_height,position_style,is_open")
->table("__BANNER__ bn,__BANNER_COLUMN__ bc")->where("bn.pid = bc.id and pid=$pid and is_show = 1 and is_open = 1")
->order("bn.orderby asc,id")->cache(true,WEBSHOP_CACHE_TIME)->limit("'.$limit.'")->select();';
$str .= '
$c = '.$limit.'- count($result); // 如果要求数量 和实际数量不一样 添加默认广告
if($c > 0)
{
$item = array(
"ad_link" => "http://www.webshop.com",
"ad_width"=>$result[0]["ad_width"],
"ad_height"=>$result[0]["ad_height"],
"ad_name" =>"暂无广告图片",
"is_open"=>1,
"target" => 0,
"bgcolor"=>"#747474",
);
if($c < "'.$limit.'"){
for($i = 0; $i < $c; $i++) // 广告数少于实际要求
{
array_push($result,$item);
}
}else{
$bc = M("BannerColumn")->find("'.$pid.'");
for($i = 0; $i < $c; $i++) // 还没有添加任何广告
{
$item["ad_width"] = $bc["ad_width"];
$item["ad_height"] = $bc["ad_height"];
array_push($result,$item);
}
}
}
';
$str .= 'foreach($result as $'.$key.'=>$'.$item.'):?>';
$str .= $this->tpl->parse($content);
$str .= '<?php endforeach; ?>';
return $str;
}
3自定义标签说明:
该自定义标签关联了两个表Banner 广告位表,BannerColumn广告表,广告位是广告的分类表,广告由广告位限制。
4自定义标签使用 <adv type="2" item="v" pid="2" limit="12">
<if condition="$v['is_open'] eq 1">
<li>
<a href="{$v.ad_link}" <if condition="$v['target'] eq 1">target="_blank"</if>>
<img src="{:apiP($v['ad_code'],195,65)}" width="195" height="65" title="{$v['ad_name']}" style="<neq name='v.position_style' value=''>{$v[position_style]};</neq>background-color:{$v[bgcolor]}" />
</a>
</li>
</if>
</adv> 该自定义标签为adv,pid为广告位分类id,limit为显示数量位12,type=2为多图显示。