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. Apr 18 '19 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>

This is how to do it:

{{ link(item.title, item.url, { 'class': ['text-blue500', 'text-3xl'] }) }}

You will have to rebuild the link(a href tag) with relevant attributes you require. You can add class, id, download or target blank as well. Refer definition below -

function THEME_preprocess_file_link(&$variables)

  $file = $variables['file'];
  $link_text = '';
  $options = array();
  $file_entity = $file instanceof File ? $file : File::load($file->fid);
  $url = file_create_url($file_entity
   // Use the description as the link text if available.
  if (empty($variables['description'])) {
    $link_text = $file_entity
  else {
    $link_text = $variables['description'];
    $options['attributes']['title'] = $file_entity

  $variables['attributes']->addClass(array('cta'));//Adding class to span
  $options['attributes']['download'] = TRUE;//Adding attribute to l
  $options['attributes']['target'] = array('_blank');//Adding attribute to l
  $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));

  • The question asks about a link field. Your answer is for a link to a file.
    – John
    Aug 19 '20 at 0:05

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .