Search code examples
symfonytwigknpmenubundle

setAttributes method of KnpMenuBundle doesn't work


I'm using KnpMenuBundle in my Symfony2 application.
I'm trying to set the menu class attribute using setAttributes of FactoryInterface of KnpMenuBundle like this:

    $menu = $factory->createItem('root');
    $menu->setAttribute('class' , 'sf-menu');

But this doesn't work! and the resulting markup with or without the setAttribute line is:

<ul>
    <li class="first">
     ...
</ul>

while I expect to have <ul class='sf-menu'>

What is the problem?


Solution

  • If you want to give a class to li elements, you have to set it this way:

    $menu->addChild('Label', [
        ...
        'attributes' => ['class' => 'sf-menu'],
    ]);
    

    If you want to give a class to your ul element:

    $menu = $this->factory->createItem('root');
    $menu->setChildrenAttribute('class', 'sf-menu');