3

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)}}
  </li>
{% endfor %}

This outputs the class on the <li>:

<li class="link-1">

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

item.attributes.addClass('link-'~loop.index)

So the result I am looking for will be:

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

You can try code below:

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

more detail about attributes in twig and link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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