## 在首页模板中获取所有的产品分类
View: 在网站经常要用到调用所有的栏目,包含下级分类的方法,这个是框架没有的,需要自己写方法实现
> \themes\hx\portal\index.html
<div class="gzcx_k_nr clearfix">
<div class="gzcx_k_nr_l">
<h4>产品中心</h4>
<div class="panel-group wrap" id="accordion" role="tablist" aria-multiselectable="true">
<php>getCategoryAll(26);</php>
</div>
<div class="gzcx_k_nr_l_dh">
24小时服务热线
<span>{$theme_vars.last_kfrx|default=''}</span>
</div>
</div>
<div class="gzcx_k_nr_r">
<ul class="clearfix">
<php>
$cid="";
$arr = json_decode(\app\portal\service\ApiService::allSubCategoriesCid(26),true);
foreach ( $arr as $key => $val) {
if( is_array($val) ) foreach( $val as $value) $cid.= $value.',';
}
if(!$cid){ $cid=26; }
</php>
<portal:articles limit="6" order="post.published_time DESC" categoryIds="$cid">
<li><a href="{:url('portal/Article/index',array('id'=>$vo.id,'cid'=>$vo.category_id))}"> <span class="gzcx_k_nr_r_img"><img src="{:cmf_get_image_url($vo.more.thumbnail)}"></span> <small>{$vo.post_title}</small></a></li>
</portal:articles>
</ul>
</div>
</div>
创建公共方法便于内页调用 getCategoryAll()
> \app\common.php
/*
获取所有的下级分类
*/
function getCategoryAll($cid){
$arr = json_decode(\app\portal\service\ApiService::subCategories($cid,'id,name'),true);
foreach ( $arr as $key => $val) {
$nr="";
$nr.="<div class=\"panel\"><div class=\"panel-heading\" role=\"tab\" id='a$key'>";
$nr.="<h4 class=\"panel-title\">";
$nr.="<a role=\"button\" data-toggle=\"collapse\" data-parent=\"#accordion\" href='#a1$key'>".$val['name'] ;
$nr.=" <i class=\"fa fa-angle-down\"></i> </a></h4></div>";
$bs = ($key==0) ?"in" :"";
$nr.= "<div id='a1$key' class=\"panel-collapse collapse $bs \" role=\"tabpanel\" aria-labelledby='a$key'> <div class=\"panel-body\"><ul class=\"clearfix\">" ;
//遍历所有的子分类,获取下级
$arr2 = json_decode(\app\portal\service\ApiService::subCategories($val['id'],'id,name'),true);
foreach ( $arr2 as $key => $val2) {
$url = url('portal/List/index',['id'=>$val2['id']]);
$nr.= "<li><a href=\"$url\"><i class=\"fa fa-angle-double-right\"></i> $val2[name]</a></li>";
}
$nr .= "</ul></div></div>" ;
$nr .= "</div>" ;
echo $nr;
}
}
### 方法说明:
#### 这里的 subCategories() 是调用框架写好的方法 返回指定分类下的子分类;在页面转成数组后,遍历得出二级的分类,结合页面样式实现的功能。另类解决方案,个人建议用AJAX实现类似方法