phpsymfonyknpmenubundleknpmenu

KnpMenuBundle - how can i set an icon class to each elements of menu?


I want to my view code looks like this:

<li>
    <a href="path/to/action">
            <i class="icon-class"></i>
            <span class="title">Title</span>
    </a>
</li>

I create menu elements by Menu Builder:

class Builder extends ContainerAware
{
    public function adminMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');

        $menu->addChild('Dashboard', array(
            'route' => 'admin_dashboard',
        ));

        return $menu;
    }
}

I have overwritten view with following code (knp_menu.html.twig):

{% block linkElement %}
    {% import _self as knp_menu %}
    <a href="{{ item.uri }}"{{ knp_menu.attributes(item.linkAttributes) }}>
        <i class="icon-class"></i>
        <span class="title">{{ block('label') }}</span>
    </a>
{% endblock %}

How can i pass a value of icon class name to <i> element in method adminMenu(), in Builder class? What is the most simple way to do it?


Solution

  • You can add any attribute you want with

    $menu->addChild('Dashboard', array(
        'route' => 'admin_dashboard',
    ))->setAttribute('icon', 'icon-class');
    

    then

    {{ item.attribute('icon') }}