Skip to main content
1 of 2
4uk4
  • 101.7k
  • 7
  • 173
  • 217

There are two ways to add attributes to the <a> tag of a link, in the options of the url object or in #attributes of a link render element.

As I don't know how you can achieve the first in twig and to avoid an extra preprocess hook to do this in php, here is how you can replace the link function with a link render element in twig:

{% for item in items %}
  <li{{ item.attributes }}>

    {% set link = {
      '#type':       'link',
      '#url':        item.url,
      '#title':      item.title,
      '#attributes': { class: ['link-class1', 'link-class2'] },
    } %}

    {{ link }}

    {% if item.below %}
      {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
    {% endif %}

  </li>
{% endfor %}
4uk4
  • 101.7k
  • 7
  • 173
  • 217