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

Profile picture for user Phil Frilling
By Phil Frilling, 2 September, 2016
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.

  use Drupal\Core\Link;
  use Drupal\Core\Url;

/**
 * Implements template_preprocess_field().
 */
function THEME_preprocess_file_link(&$variables) {

  $url = file_create_url($variables['file']->getFileUri());

  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    $link_text = $variables['file']->getFilename();
  }
  else {
    $link_text = $variables['description'];
    $options['attributes']['title'] = $variables['file']->getFilename();
  }

  $options['attributes']['class'] = array('button', 'icon', 'icon-pdf');

  $variables['link'] = Link::fromTextAndUrl($link_text, Url::fromUri($url, $options))->toString();
}