I'm trying to apply a button class to the {{ link }} attribute in code below.

<span{{attributes}}><a class="usa-button"{{ link }}</span>

It displays correctly however the markup is not correct. I see an extra <a="" tag.

<a class="usa-button" <a="" href="http://sites.localhost/sites/default/files/Image%20styles%20for%20grid%20view_3.docx" type="application/vnd.openxmlformats-officedocument.wordprocessingml.document; length=14535">Image styles for grid view_3.docx</a>

Any ideas on how to apply class cleanly?

  • Since you're in Twig, I think what you're looking for is this: drupal.stackexchange.com/a/260232/79805. If not Twig, the other answers should work. In twig, you'd be looking for attributes.addClass(), but you cannot apply it with the above template. The reason you see two <a> tags is that {{ link }} contains an <a> tag itself. If you want to apply the class via Twig with addClass() you will need a new template for your link field. – Prestosaurus Apr 18 at 0:24

I think your easiest approach would be to modify the field template and add a wrapping span with classes you need.


{% for item in items %}
  <span{{ item.attributes.addClass('my-class') }}>{{ item.content }}</span>
{% endfor %}

or replace span and content with to add class directly to <a> tag:

<a href="{{ item.content['#url']}}" class="my-class">{{ item.content['#title'] }}</a>

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.