Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 699
klapaucius Avatar asked Jan 02 '15 19:01

klapaucius


2 Answers

You can add any attribute you want with

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

then

{{ item.attribute('icon') }}
like image 66
Federkun Avatar answered Nov 16 '22 12:11

Federkun


I'd suggest the use of extras instead of attributes, because attributes is used to render the li element's attributes.

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

and

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

will probably be rendered as:

<li icon="icon-class"><a href="#"><i class="fa fa-icon-class" aria-hidden="true"></i> Dashboard</a></li>

Whereas:

$menu->addChild('Dashboard', array(
    'uri' => '#',
))->setExtra('icon', 'icon-class');

and

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

Will probably just be rendered as:

<li><a href="#"><i class="fa fa-icon-class" aria-hidden="true"></i> Dashboard</a></li>

Also see this answer: https://stackoverflow.com/a/19095287/2106834.

like image 5
Jonny Avatar answered Nov 16 '22 11:11

Jonny