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 vendorKnpMenusrcKnpMenuResourcesviewsknp_menu.html.twig
into your AcmeAcmeBundleResourcesviewsMenuknp_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'}) }}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…