klapaucius klapaucius - 1 year ago 126
PHP Question

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

I want to my view code looks like this:

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

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>
{% endblock %}

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

Answer Source

You can add any attribute you want with

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


{{ item.attribute('icon') }}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download