How to append css class to menu link? 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 %}
      &lt;ul{{ attributes.addClass('menu') }}&gt;
    {% else %}
      &lt;ul class="menu"&gt;
    {% 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',
        ]
      %}
      &lt;li{{ item.attributes.addClass(classes) }}&gt;
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      &lt;/li&gt;
    {% endfor %}
    &lt;/ul&gt;
  {% endif %}
{% endmacro %}
This is an easy one, I'm pretty sure you might have figured out yourself in a short while.

You see that set classes directive?

{%
  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 = [
    'myCssClass',
    'menu-item',
    item.is_expanded ? 'menu-item--expanded',
    item.is_collapsed ? 'menu-item--collapsed',
    item.in_active_trail ? 'menu-item--active-trail',
  ]
%}


Leaving the rest of the template untouched (especially the {{ item.attributes.addClass(classes) }}) gives you the desired behavior.

Some further reading, that might be of interest for you: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates