How to add a div to KnpMenu (Symfony2.1)

2.3k Views Asked by At

I would like to make a drowdown box whenever someone hovers over a menu button, im generating the menu with the KnpMenuBundle.

What i would like to get is a structure like this:

<lu>
    <li><a>...</a></li>
    <li>
        <a>...</a>
        <div>...</div>
    </li>
    <li><a>...</a></li>
<lu>

If possible i would like to render a controller from inside the div.

Can this be done?

If i missed something in the documentation please post a link because i have been searching for hours...

1

There are 1 best solutions below

2
On BEST ANSWER

It can be done, and I once did exactly this, but whether this sort of thing should be done using KnpMenuBundle I'm not too sure! Anyway, I achieved this by defining my MenuBuilder class as a service and injecting the @templating service. This doesn't call a controller action as you mentioned, but allows you to render any template you wish...

/**
 * @param Request $request
 * @return \Knp\Menu\ItemInterface
 */
protected function createUserMenuLoggedOut(Request $request)
{
    $menu = $this->factory->createItem('root');

    $signInItem = $menu->addChild('Sign in', array('route' => 'fos_user_security_login'));
    $signInItem
        ->setLinkAttributes(array(
            'id' => 'sign-in-link',
            'class' => 'dropdown-toggle',
            'data-toggle' => 'dropdown',
            'data-target' => '#signin'
        ))
        ->setAttributes(array(
            'id' => 'signin',
            'class' => 'dropdown'
        ))
    ;

    // THIS IS THE LINE YOU'RE INTERESTED IN
    $signInItem->addChild($this->templating->render('ApplicationSonataUserBundle:Security:login_options.html.twig'));

    // more menu items...

    return $menu;
}

If I recall correctly, I think this ended up wrapping the template in an additional <ul>...</ul> but this didn't cause much of a problem after a bit of styling.