We have a custom menu mymenu
where we use menu_link_attributes to add CSS classes per menu link.
The problem we are running into is that we have one generic css class that we always want added regardless of whether it is entered through the Menu link attributes. In the twig template, it is using {{ link(item.title, item.url) }}
.
We tried the following, but it will only replace myCssClass
with whatever was their before and I cannot seem to find the right array when calling mymodule_preprocess_menu()
.
{{ link(item.title, item.url, item.attributes.addClass('myCssClass')) }}
How can I append a CSS class to a menu link to the item.attributes
array?
menu--mymenu.html.twig
{{ menus.menu_links(items, attributes, 0) }}
{% macro menu_links(items, attributes, menu_level) %}
{% import _self as menus %}
{% if items %}
{% if menu_level == 0 %}
<ul{{ attributes.addClass('menu') }}>
{% else %}
<ul class="menu">
{% endif %}
{% for item in items %}
{%
set classes = [
'menu-item',
item.is_expanded ? 'menu-item--expanded',
item.is_collapsed ? 'menu-item--collapsed',
item.in_active_trail ? 'menu-item--active-trail',
]
%}
<li{{ item.attributes.addClass(classes) }}>
{{ link(item.title, item.url) }}
{% if item.below %}
{{ menus.menu_links(item.below, attributes, menu_level + 1) }}
{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
{% endmacro %}