Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 361
Dylan van der Graaf Avatar asked Sep 24 '17 13:09

Dylan van der Graaf


2 Answers

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');
}
like image 187
Shevy Avatar answered Sep 17 '22 23:09

Shevy


You can add a class to each child items when you add it like that:

$menu->addChild('Home', ['route' => 'homepage'])
     ->setAttributes(array(
         'class' => 'nav-item'
     ));
like image 35
YaatSuka Avatar answered Sep 18 '22 23:09

YaatSuka