Search code examples
phpsymfonytwigknpmenubundle

Override KnpMenu submenu items


I have made a menu with KnpMenu and I'm trying to override the submenu

This is how I add submenu items

$menu
    ->addChild('sidebar.front.servers', ['route' => 'server_index'])
    ->setExtras([
        'icon'               => 'fa fa-hdd-o',
        'regex'              => '#^/servers/#',
    ])
;
$menu['sidebar.front.servers']
    ->addChild('nnanana', ['route' => 'server_index'])
;

I searched on the knp_menu.html.twig to find what is rendering the submenu.

I have find this who render submenu list and items.

{% block list %}
    {% if item.hasChildren and options.depth is not same as(0) and item.displayChildren %}
        {% import _self as knp_menu %}
        <ul{{ knp_menu.attributes(listAttributes) }}>
            {{ block('children') }}
        </ul>
     {% endif %}
{% endblock %}

{% block children %}
    {# save current variables #}
    {% set currentOptions = options %}
    {% set currentItem = item %}
    {# update the depth for children #}
    {% if options.depth is not none %}
        {% set options = options|merge({'depth': currentOptions.depth - 1}) %}
    {% endif %}
    {# update the matchingDepth for children #}
    {% if options.matchingDepth is not none and options.matchingDepth > 0 %}
    {% set options = options|merge({'matchingDepth': currentOptions.matchingDepth - 1}) %}
    {% endif %}
    {% for item in currentItem.children %}
        {{ block('item') }}
    {% endfor %}
    {# restore current variables #}
    {% set item = currentItem %}
    {% set options = currentOptions %}
{% endblock %}

This put classes on submenu list.

{%- set childrenClasses = item.childrenAttribute('class') is not empty ? [item.childrenAttribute('class')] : [] %}
{%- set childrenClasses = childrenClasses|merge(['menu_level_' ~ item.level]) %}
{%- set listAttributes = item.childrenAttributes|merge({'class': childrenClasses|join(' ') }) %}

This render all the submenu items

{{ block('list') }}

But when I'm trying to override this block in my template, like this

{% block item %}
    {% import 'knp_menu.html.twig' as knp_menu %}
    <a href="#">test</a>
{% endblock %}

This is not working and menu is not rendered anymore, I only have test displayed...

I do exactly the same to override every menu items and this work.

How can I override this submenu ?

Thanks


Solution

  • I find the way to override submenu items.

    Submenu items are rendered with the same code as main menu items.

    So to override it just add a twig condition like this and do whatever you want inside

    {% if item.hasChildren and options.depth is not same as(0) and item.displayChildren %}
        <a href="#">
        <i class="{{ item.extra('submenu-icon') }}"></i>
    {% else %}