Skip to main content

Drupal 8: Add a class to a file fields link.

I needed to add a 'button' class to a file field link and ran into the following issue:

https://www.drupal.org/node/2575427

I was unable to alter the actual anchor within the twig template. So, to workaround the issue, I added the following code to my .theme file.

  1.   use Drupal\Core\Link;
  2.   use Drupal\Core\Url;
  3.  
  4. /**
  5.  * Implements template_preprocess_field().
  6.  */
  7. function THEME_preprocess_file_link(&$variables) {
  8.  
  9.   $url = file_create_url($variables['file']->getFileUri());
  10.  
  11.   // Use the description as the link text if available.
  12.   if (empty($variables['description'])) {
  13.     $link_text = $variables['file']->getFilename();
  14.   }
  15.   else {
  16.     $link_text = $variables['description'];
  17.     $options['attributes']['title'] = $variables['file']->getFilename();
  18.   }
  19.  
  20.   $options['attributes']['class'] = array('button', 'icon', 'icon-pdf');
  21.  
  22.   $variables['link'] = Link::fromTextAndUrl($link_text, Url::fromUri($url, $options))->toString();
  23. }


Comments