I am trying to add classes to the <a> tag output from menu.html.twig. I can add these classes to the <li>, but not the <a> tag.

In the twig file I have a loop and I need to add the classes 'link-1', 'link-2' etc to each <a> tag:

{% for item in items %}
  <li{{ item.attributes.addClass('link-'~loop.index) }}>
    {{ link(item.title, item.url)}}
{% endfor %}

This outputs the class on the <li>:

<li class="link-1">

How do I set the code below on the <a> tag instead?


So the result I am looking for will be:

<li><a class="link-1">Link Text</a></li>

1 Answer 1


You can try code below:

{% for item in items %}
      set attributes = attributes.setAttribute('class', 'link-'~loop.index)
    {{ link(item.title, item.url, attributes)}}
{% endfor %}

more detail about attributes in twig and link


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.