Add Class to knp menu root Element with Twig

hereandnow78 picture hereandnow78 · Jun 18, 2014 · Viewed 11.4k times · Source

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

Answer

qooplmao picture qooplmao · Jun 18, 2014

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' }) }}