Code snippet that can be used to append css class to menu link in twig file in Drupal 8.
Question:
How to append css class to menu link item?
Solution:
You see that set classes
directive in menu.html.twig ?
{%
set classes = [
'menu-item',
item.is_expanded ? 'menu-item--expanded',
item.is_collapsed ? 'menu-item--collapsed',
item.in_active_trail ? 'menu-item--active-trail',
]
%}
This is where the magic happens and the classes array is built for all CSS classes to attach to your link item(s).
And this is also the place where you should add your additional CSS class that should be used in every link item, like so:
{%
set classes = [
'my-custom-css-class',
'menu-item',
item.is_expanded ? 'menu-item--expanded',
item.is_collapsed ? 'menu-item--collapsed',
item.in_active_trail ? 'menu-item--active-trail',
]
%}