1

I'd like to add classes to <a>-tags for menu items that have a submenu.

Currently this is my code, I can only add classes to <li> elements:

{{ 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('nav navbar-nav navbar-right') }}>
    {% else %}
      <ul class="dropdown-menu panel-collapse collapse">
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          item.is_expanded ? 'menu-item--expanded dropdown panel simple-dropdown',
          item.is_collapsed ? 'collapsed',
          item.in_active_trail ? 'active',
        ]
      %}
      <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 %}

1 Answer 1

4

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 %}

Edit:

I just found out, that in contrast to the php function l() the twig function link() does provide a 3rd parameter to add attributes, so this is a much easier solution:

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

    {{ link(item.title, item.url, { class: ['link-class1', 'link-class2'] }) }}

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

  </li>
{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.