function FileThemeHooks::preprocessFileLink

Prepares variables for file link templates.

Default template: file-link.html.twig.

Parameters

array<string,mixed> $variables: An associative array containing:

  • file: A File entity to which the link will be created.
  • icon_directory: (optional) A path to a directory of icons to be used for files. Defaults to the value of the "icon.directory" variable.
  • description: A description to be displayed instead of the filename.
  • attributes: An associative array of attributes to be placed in the a tag.

File

core/modules/file/src/Hook/FileThemeHooks.php, line 90

Class

FileThemeHooks
Theme hooks for the file module.

Namespace

Drupal\file\Hook

Code

public function preprocessFileLink(array &$variables) : void {
  $file = $variables['file'];
  $options = [];
  $url = $this->fileUrlGenerator
    ->generate($file->getFileUri());
  $mime_type = $file->getMimeType();
  $options['attributes']['type'] = $mime_type;
  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    $link_text = $file->getFilename();
  }
  else {
    $link_text = $variables['description'];
    $options['attributes']['title'] = $file->getFilename();
  }
  // Classes to add to the file field for icons.
  $classes = [
    'file',
    // Add a specific class for each and every mime type.
'file--mime-' . strtr($mime_type, [
      '/' => '-',
      '.' => '-',
    ]),
    // Add a more general class for groups of well known MIME types.
'file--' . IconMimeTypes::getIconClass($mime_type),
  ];
  // Set file classes to the options array.
  $variables['attributes'] = new Attribute($variables['attributes']);
  $variables['attributes']->addClass($classes);
  $variables['file_size'] = $file->getSize() !== NULL ? ByteSizeMarkup::create($file->getSize()) : '';
  $variables['link'] = (new Link($link_text, $url->mergeOptions($options)))
    ->toRenderable();
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.