使用laravel-menu,如何让子项嵌套?

时间:2016-02-07 00:59:06

标签: php laravel laravel-5

我正在使用Lavary's laravel-menu package,我正在尝试根据db表的内容构建一个简单的2级菜单系统。我创建了中间件来为每个请求创建菜单:

public function handle($request, Closure $next)
{
    Menu::make('NavBar', function($menu){
        $menuitems = MenuItem::all();
        foreach($menuitems as $menuitem)
        {
            if(!is_null($menuitem->parent)){
               // For example, 'Conferences', a top level menu item with a null parent field
               $menu->add($menuitem->title, url($menuitem->url));
            }
            else{
                // Parent is a field in database, for example 'Traverse City 2015' would have the parent 'conferences'
                $parent = $menuitem->parent;
                $menu->item($parent)->add($menuitem->title, url($menuitem->url));

            }
        }
    });
    return $next($request);
}

在我看来,我打电话给:

{!! $NavBar->asUl() !!}

我希望这样做:

<ul>
  <li><a href="/conferences">Conferences</a></li>
  <ul>
    <li><a href="/conferences/traverse-city-2015">Traverse City 2015</li>
  </ul>
</ul>

相反,它正在渲染:

<ul>
  <li><a href="/conferences/">Conferences</a></li>
  <li><a href="/conferences/traverse-city-2015">Traverse City 2015</a></li>
</ul>

为什么子项目没有正确显示的任何想法?

1 个答案:

答案 0 :(得分:3)

您所追求的是嵌套组:https://github.com/lavary/laravel-menu#nested-groups

Menu::make('MyNavBar', function($menu){
    $menu->group(array('prefix' => 'pages', 'data-info' => 'test'), function($m){

        $m->add('About', 'about');

        $m->group(array('prefix' => 'about', 'data-role' => 'navigation'), function($a){

            $a->add('Who we are', 'who-we-are?');
            $a->add('What we do?', 'what-we-do');
            $a->add('Our Goals', 'our-goals');
        });
    });

});

然后呈现为:

<ul>
    <li data-info="test">
    <a href="http://yourdomain.com/pages/about">About</a>
        <ul>
            <li data-info="test" data-role="navigation"><a href="http://yourdomain.com/pages/about/who-we-are"></a></li>
            <li data-info="test" data-role="navigation"><a href="http://yourdomain.com/pages/about/what-we-do"></a></li>
            <li data-info="test" data-role="navigation"><a href="http://yourdomain.com/pages/about/our-goals"></a></li>
        </ul>
    </li>
</ul>