Search code examples
symfonybootstrap-4knpmenubundle

KnpMenuBundle not working with Bootstrap 4 navbar


I am currently making a menu with the Symfony bundle: KnpMenuBundle. I am using Bootstrap 4 as stylesheet.

Bootstrap 4 requires each list item in the navbar to have the class 'nav-item':

<li class="nav-item active"> <-- this
    <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>

I can't seem to figure out how to add the class 'nav-item' to the list item with KnpMenuBundle. Currently I see this when I load the page: navbar result

This is my Builder class in src/AppBundle/Menu:

namespace AppBundle\Menu;


use Knp\Menu\MenuFactory;

class Builder
{
    public function mainMenu(MenuFactory $factory, array $optioins)
    {
        $menu = $factory->createItem('root');
        $menu->setChildrenAttribute('class', 'navbar-nav mr-auto');
        $menu->addChild('Home', ['route' => 'homepage']);
        $menu->setChildrenAttributes(['class' => 'nav-item']);
        return $menu;
    }
}

My code in base.html.twig to generate menu:

{{ knp_menu_render('AppBundle:Builder:mainMenu', {'currentClass': 'active'}) }}

What do I do to make it working?


Solution

  • I did this to get top level correct. Haven't worked out dropdowns yet though.

    $menu->setChildrenAttribute('class', 'navbar-nav');
    // menu items
    foreach ($menu as $child) {
        $child->setLinkAttribute('class', 'nav-link')
            ->setAttribute('class', 'nav-item');
    }