function template_preprocess_file_link

Same name and namespace in other branches
  1. 9 core/modules/file/file.module \template_preprocess_file_link()
  2. 10 core/modules/file/file.module \template_preprocess_file_link()
  3. 11.x core/modules/file/file.module \template_preprocess_file_link()

Prepares variables for file link templates.

Default template: file-link.html.twig.


array $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 "" variable.
  • description: A description to be displayed instead of the filename.
  • attributes: An associative array of attributes to be placed in the a tag.


core/modules/file/file.module, line 1518


function template_preprocess_file_link(&$variables) {
    $file = $variables['file'];
    $options = [];
    // @todo Wrap in file_url_transform_relative(). This is currently
    // impossible. As a work-around, we currently add the '' cache context
    // to ensure different file URLs are generated for different sites in a
    // multisite setup, including HTTP and HTTPS versions of the same site.
    // Fix in
    $url = $file->createFileUrl(FALSE);
    $variables['#cache']['contexts'][] = '';
    $mime_type = $file->getMimeType();
    // Set options as per anchor format described at
    $options['attributes']['type'] = $mime_type . '; length=' . $file->getSize();
    // 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 = [
        // 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--' . file_icon_class($mime_type),
    // Set file classes to the options array.
    $variables['attributes'] = new Attribute($variables['attributes']);
    $variables['file_size'] = format_size($file->getSize());
    $variables['link'] = Link::fromTextAndUrl($link_text, Url::fromUri($url, $options))->toRenderable();

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