很多导航菜单是树形的,即一级一级往下细分,这样的结构固然需要用递归来处理。
对于Freemarker 来说,宏就相当于函数,其定义了签名及参数列表。
所以在页面应这样写:
<ul>
<!-- 递归 宏定义 -->
<#macro bpTree children>
<#if children?? && children?size gt 0>
<#list children as child>
<#if child.children?? && child.children?size gt 0>
<li class="treeview">
<a href="javascript:void(0)">
<i class="${(child.mIcon=='')?string('fa fa-share',child.mIcon) }" aria-hidden="true"></i> <span>${child.mCname}</span>
<i class="fa fa-angle-left pull-right" aria-hidden="true"></i>
</a>
<ul class="treeview-menu">
<@bpTree children=child.children />
</ul>
</li>
<#else>
<li><a href="javascript:void(0)" onclick="loadContent('${child.mUrl}')"><i class="${ (child.mIcon=='')?string('fa fa-circle-o',child.mIcon) }" aria-hidden="true"></i> ${child.mCname}</a></li>
</#if>
</#list>
</#if>
</#macro>
<!-- 调用宏 生成递归树 -->
<@bpTree children=treeMenu />
</ul>
treeMenu是Controller返回的JSON中的根元素,其值是JSONArray,所以最关键的核心问题是如何生成递归地数据结构。叶子节点的children为空数组。
Fremarker 宏 请参考博文:Freemarker定义宏的用法
后台Service查询数据库处理数据生成JSONArray的数据结构格式:
[
{
"mCname": "框架应用管理",
"mIcon": "fa fa-square-o",
"mAppid": 1,
"mIsclose": 0,
"mIssys": 1,
"mUrl": "",
"children": [
{
"mCname": "模块管理",
"mIcon": "fa fa-cube",
"mAppid": 1,
"mIsclose": 0,
"mIssys": 1,
"mUrl": "AppMgr/ModuleManager/default.aspx",
"children": [],
"mOrderlevel": "0001",
"mParentName": "框架应用管理",
"mParentid": 1,
"moduleid": 2,
"mModulecode": "S00M00",
"aAppName": "框架应用管理"
},
{
"mCname": "配置管理",
"mIcon": "fa fa-cog",
"mAppid": 1,
"mIsclose": 0,
"mIssys": 1,
"mUrl": "AppMgr/ConfigManager/default.aspx",
"children": [],
"mOrderlevel": "0002",
"mParentName": "框架应用管理",
"mParentid": 1,
"moduleid": 3,
"mModulecode":