2

我的问题与以下有关,这是“正确”的方式还是有更好的解决方案?

Symfony2 KnpMenuBundle:设置激活一个菜单项,即使它不在该菜单上

那是我当前的代码:

public function mainMenu(FactoryInterface $factory, array $options)
{
    $menu = $factory->createItem('root');
    $menu->setChildrenAttributes(array('class' => 'nav navbar-nav'));
    $menu->addChild('Home',
        array('route' => 'home'
    ));
    $menu->addChild('Producers',
        array(
        'route' => 'producers_show'
    ));
    $menu->addChild('Ships',
        array(
            'route' => 'ships_show'
        ));

    /* not working */
       $request = $this->container->get('request');
       $routeName = $request->get('_route');
       switch ($routeName)
       {

           case 'producer_create':
           case 'ship_create':
                 $menu->setCurrent(true);
           break;
       }

    return $menu;
}

路线“ship/create”的渲染 HTML 如下所示

<ul class="nav navbar-nav">
    <li class="first">        
        <a href="/app_dev.php/">Home</a>        
    </li>
    <li>        
         <a href="/app_dev.php/producers">Producers</a>        
    </li>
    <li class="last">        
         <a href="/app_dev.php/ships">Ships</a>        
    </li>
</ul>

如您所见,没有设置“活动”我是否必须将子操作(例如创建更新删除)添加到菜单中,然后隐藏它们?请问我该如何解决这个问题?

4

1 回答 1

3

您的代码的问题是您$menu每次都将根项设置为当前项。

switch (true)
{
    case preg_match('/^producer(s)?_/', $routeName):
        // setting Producers as the current
        $menu->getChild('Producers')->setCurrent(true);
        break;

    case preg_match('/^ship(s)?_/', $routeName):
        // setting Ships as the current
        $menu->getChild('Ships')->setCurrent(true);
        break;

    default:
        $menu->setCurrent(true);
}
于 2014-01-18T08:43:09.993 回答