我的问题与以下内容有关, 这是“正确的”方式还是有更好的解决方案?
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>
正如您所看到的,没有任何内容设置为“有效” 我是否必须在菜单中添加创建更新删除等子操作,并隐藏它们? 我该如何解决这个问题?
答案 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);
}