How can you display document file sizes next to a media link button? I'm trying to display the file size of a file next to a media link button on a page.

I have two content types with a media entity reference field in each. Each field is restricted to only pull from a file media type. What I was trying to do was create a twig variable using a field preprocess and pop that variable inside each of my field templates. However, my preprocess below doesn't seem to be displaying the file size as I want. What am I doing wrong?

function theme_preprocess_field(&amp;$variables, $hook) {

  $pdf_fields = [
    'field_1',
    'field_2'
  ];

  if (in_array($element['#field_name'], $pdf_fields) &amp;&amp; $element['#entity_type'] == 'node') {

    if ($variables['items'][0]) {

      $field_name = $element['#field_name'];

      $node = $element['#object'];
      // Get first referenced media id.
      $media_id = $node-&gt;$field_name-&gt;target_id;
      // Get file object.
      $file = \Drupal\file\Entity\File::load($media_id);
      if ($file) {
        // Get file size.
        $file_size = format_size($file-&gt;getSize());
        // Set file size variable.
        $variables['file_size'] = $file_size;
      }
    }
  }
}


Twig field template 

{% for item in items %}
  &lt;a href="{{ item.content['#url'] }}" class="button"&gt;Download Paper&lt;/a&gt;&lt;span&gt;(PDF | {{ file_size }})&lt;/span&gt;
{% endfor %}
function HOOK_preprocess_file_link(&amp;$variables) {
  if (isset($variables['file'])) {
    $variables['fileLinkDisplay'] = [
      'fileSize' =&gt; $variables['file']
        -&gt;getSize(),
      'fileSizeFormatted' =&gt; format_size($variables['file']
        -&gt;getSize()),
    ];
  }
}


{{ fileLinkDisplay.fileSize }}and {{ fileLinkDisplay.fileSizeFormatted }} will be available in your template.

PS: if it works then you can more filter to restrict to the content type and field you want applied for.

Additionally, there is a module that show the size https://www.drupal.org/project/field_formatter_file_size


  Field Formatter File Size is a field formatter to display the file
  size.