KnpMenuBundle,即使对于子操作,也保持主菜单处于活动状态

时间:2014-01-17 14:46:34

标签: symfony twig knpmenubundle

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

Symfony2 KnpMenuBundle: set active a menu item even when its not on that menu

这是我目前的代码:

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;
}

呈现的HTML对于路线“ship / create”

,如下所示
<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>

正如您所看到的,没有任何内容设置为“有效” 我是否必须在菜单中添加创建更新删除等子操作,并隐藏它们? 我该如何解决这个问题?

1 个答案:

答案 0 :(得分: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);
}