45

How to customize KNPMenuBundle?

I can't figure out how to add an image or a span tag using the KnpMenuBundle.

I simply want this:

<ul>
    <li>
         <img src="{{asset('bundles/mybundle/images/my_image.png')}} /">
         <span>My Title</span>        
     </li>
</ul>

In the MenuBuilder, this would start with:

$menu->addChild('My Title');

How could I add the image in the <li> statement?


EDIT: THE EASY WAY

There is actually an easy way to do this within the bundle:

1 Copy the template vendor\KnpMenu\src\Knp\Menu\Resources\views\knp_menu.html.twig into your Acme\AcmeBundle\Resources\views\Menu\knp_menu.html.twig and extend it as follow:

{% extends 'knp_menu.html.twig' %}


2 Modify the template according to your needs. For example, if you decide to add a span tag each time you use $menu->addChild('Your Title');, simply add the span tag between <a></a>:

{% block linkElement %}
    <a href="{{ item.uri }}"{{ _self.attributes(item.linkAttributes) }}>
        <span>{{ block('label') }}</span>
    </a>
{% endblock %}


3 You can now choose your custom layout when using the menu:

{{ knp_menu_render('main', {'template': 'AcmeBundle:Menu:knp_menu.html.twig'}) }}
Mick
  • 30,759
  • 16
  • 111
  • 130
  • 3
    Why not define an attribute of the `
  • ` or `` element and add the image in css ?
  • – j0k Jun 27 '12 at 13:53
  • 5
    "The Easy Way" listed above is awesome. Thanks. – Kevin Feb 09 '13 at 16:47
  • I wanted to put the "knp_menu.html.twig" in the "app/Resouces/views" directory. This doesn't work. What can be the mistake ? – Slowwie Feb 18 '14 at 14:44
  • As @DARSC0D3 have said in his [answer](http://stackoverflow.com/a/21887674/1284485), you need to import the parent template to get the attributes working. – Plínio César May 04 '14 at 19:49
  • 1
    In addition to copying the template as above, one must also modify `config.yml` such that the `template:` line in `knp_menu:` block reads `YourBundle:Menu:knp_menu.html.twig`. – geoB Jun 26 '14 at 23:05
  • Following your instructions ends up with `Unable to find template "AppBundle:Menu:knp_menu.html.twig"`. BTW I up-voted your answer for the time you spent on providing this tutorial – Peyman Mohamadpour Mar 06 '17 at 12:20