PHP左侧菜单栏的管理与实现

时间:2023-12-09 16:29:31
以thinkPHP5.0为例

后台config.php文件里配置
//配置文件设置菜单内容属性

'menu' => [
  [
    'name' => '菜单栏1',
    'url' => '/admin/index/one',
    'status'=> 0,
    'sub'=> 0
  ],
  [
    'name' => '菜单栏2',
    'url' => '#',
    'status'=> 0,
    'sub'=>[
        [
          'name' => '子菜单栏1',
          'url' => '/admin/user/one',
          'status'=> 0,
        ],
        [
          'name' => '子菜单栏2',
          'url' => '/admin/user/two'),
          'status'=> 0,
        ],
    ]
  ],
  [
    'name'=> '菜单栏3',
    'url' => '#',
    'status'=> 0,
    'sub'=>[
        [
          'name' => '子菜单栏1',
          'url' => '/admin/admin/one',
          'status'=> 0,
        ],
        [
          'name' => '子菜单栏2',
          'url' =>url('/admin/admin/two'),
          'status' => 0,
        ],
    ]
  ],
  [
    'name' => '菜单栏4',
    'url' => '/admin/order/one',
    'status'=> 0,
    'sub'=> 0
  ]
]

  

 在项目后台初始化方法里base
class Base extends Controller
{ protected function _initialize()
{
$request = Request::instance();
if (session('uid') === null) {
$this->redirect('Simple/login');
}
$menu = Config::get('menu'); //获取配置文件里的菜单数据
$clickUrl = $request->path(); //获取当前请求的地址
$clickUrl = '/' . $clickUrl;
$menuData = setMenu($menu, $clickUrl); //对每个配置项进行状态设置
$this->assign('menu', $menuData);
}
}

  

 后台common.php文件
function setMenu($menuData,$url){
if (!is_array($menuData)){
return false;
}
foreach ($menuData as $key => $value) {
if($value['url'] == '#'){
foreach ($value['sub'] as $k => $v) {
if($v['url'] == $url){
$menuData[$key]['status'] = 1; //改变当前访问的子菜单栏状态
$menuData[$key]['sub'][$k]['status'] = 1; //改变当前当前的菜单栏状态
}
}
} else {
$menuData[$key]['status'] = 1;
}
}
return $menuData;
}

  

 布局页面上view判断菜单栏及子菜单栏的status状态 
<div class="side-content" id="sidebar-menu">
<ul class="nav-main" id="side-item">
{volist name="menu" id="vo"}
{empty name="$vo.sub"}
<li>
<a href="{$vo.url}" target="_self"><span class="sidebar-mini-hide">{$vo.name}</span></a>
</li>
{else /}
{if condition="$vo.status eq 1"}
<li class="dropdown open">
{else /}
<li class="dropdown">
{/if}
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="true">{$vo.name} <span class="caret"></span></a>
<ul class="dropdown">
{volist name="vo.sub" id="v"}
            {if condition="$v.status eq 1"}
            <li class="active">
            {else /}
            <li>
            {/if}
<a href="{$v.url}" target="_self"><span class="sidebar-mini-hide">{$v.name}</span></a>
</li>
{/volist}
</ul>
</li>
{/empty}
{/volist}
</ul>
</div>

  

PHP左侧菜单栏的管理与实现