也许您可以使用我的 KnpMenu Builder 作为示例?
namespace AppBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class Builder extends ContainerAware
{
public function mainMenu(FactoryInterface $factory, array $options)
{
$sc = $this->container->get('security.context');
$menu = $factory->createItem('root');
$menu->setChildrenAttribute('class', 'nav navbar-nav');
$menu->addChild('About us', array('route' => 'about'));
$menu->addChild('Contact', array('route' => 'contact'));
/*
* before we use isGranted() we have to check if the security is available, otherwise we will receive an exception on the custom error pages. See also
* http://symfony.com/doc/current/cookbook/controller/error_pages.html#avoiding-exceptions-when-using-security-functions-in-error-templates
*/
if($sc->getToken())
{
$menu->addChild('Members', array('uri' => '#'))
->setAttribute('dropdown', true);
if($sc->isGranted('IS_AUTHENTICATED_REMEMBERED'))
{
$menu['Members']->addChild('My profile', array('route' => 'fos_user_profile_show'));
if($sc->isGranted('ROLE_ADMIN'))
{
$menu['Members']->addChild('Dashboard', array('route' => 'sonata_admin_dashboard'))
->setAttribute('divider_append', true);
}
$menu['Members']->addChild('Logout', array('route' => 'fos_user_security_logout'));
}
else
{
$menu['Members']->addChild('Login', array('route' => 'fos_user_security_login'));
$menu['Members']->addChild('Registration', array('route' => 'fos_user_registration_register'));
}
}
return $menu;
}
}