Add Class to knp menu root Element with Twig

2019-06-15 14:14发布

问题:

what is the correct way to add a class to knp_menu's root element <ul> with twig?

i tried a lot of things:

1.

{{ knp_menu_render('main', {'class': 'foo'}) }}

2.

{{ knp_menu_render('main', {'attributes': {'class': 'foo'}}) }}

3.

{{ knp_menu_render('main', {'listAttributes': {'class': 'foo'}}) }}

4.

{{ knp_menu_render('main', {'attributes': {'listAttributes': {'class': 'foo'}}}) }}

none of them worked

回答1:

You can add it in your menu builder like..

$menu = $this->factory->createItem('root', array(
    'childrenAttributes'    => array(
        'class'             => 'foo',
    ),
));

Update

I just got a notification about this and found another way although it requires you to use a custom template to achieve it.

In your custom template you need to override the list block like..

{% block list %}
    {% if item.hasChildren and options.depth is not sameas(0) and item.displayChildren %}
        {% import 'knp_menu.html.twig' as knp_menu %}
        <ul{{ knp_menu.attributes(listAttributes|merge({'class': [
                options.rootClass is defined ? options.rootClass : '',
                listAttributes.class is defined ? listAttributes.class : ''
            ]|join(' ')
        })) }}>
            {% set options = options|merge({'rootClass': '' }) %}
            {{ block('children') }}
        </ul>
    {% endif %}
{% endblock %}

In this rather than use knp_menu.attributes(listAttributes) you pass in a array with your on-the-fly generated listAttributes.class value. This attribute is generate by joining option.rootClass (if it exists) with listAttributes.class (if it exists) as the listAttributes.class value.

The option.rootClass value is reset to '' after use using {% set options = options|merge({'rootClass': '' }) %} so that it is not added to every sub-menu.

This will allow you to render your menu using..

{{ knp_menu_render('main', {'rootClass': 'foo' }) }}


回答2:

Have not found a clean solution to pass params in view also. My solution in the builder class:

$menu->setChildrenAttribute('id', 'boo') ->setChildrenAttribute('class', 'foo');



回答3:

Try to

{% set menu = knp_menu_get('AppBundle:Builder:categoriesMenu', [], {'childrenAttributes': {'class': 'menu'}}) %}
{{ knp_menu_render(menu) }}


回答4:

{% set menu = knp_menu_get('AppBundle:Builder:mainMenu', []) %}
{% do menu.setChildrenAttribute('class', 'child-class') %}
{% knp_menu_render(menu, {'currentClass': 'active'}) %}

found here https://github.com/KnpLabs/KnpMenu/issues/166