Skip to main content
  • Guides & Documentation

Knowledgebase

Featured articles, how-to guides and quick tips.

Get Media Image URL in a Custom Block Twig Template - Drupal 8

Sometimes it may be useful to access the raw URI or file URL of an image uploaded using a Media reference field in Drupal 8.

You may require the URL for the image file rather than wanting Drupal to render the image and surrounding HTML markup with it.

To accomplish this in a custom block template using Twig, simply use the following syntax, replacing the field name with your custom Media field machine name:

{% if content.field_custom_image|render is not empty %}
  {{ file_url(content.field_custom_image.entity.field_media_image.entity.fileuri) }}
{% endif %}

Update August 2019: As of Drupal 8.7, the above syntax no longer produces the desired result. For Drupal 8.7 and above, rendering the file URL of a Media image field should be accomplished as below:

{% if content.field_custom_image|render is not empty %}
  {{ file_url(content.field_custom_image[0]['#media'].field_media_image.entity.uri.value) }}
{% endif %}

Be sure to replace the bold text in the code snippet above with the machine name of your Media image field.

This code works great if you're using a Media field type in a custom block! It's perfect for printing the specific file URI of the media file.

But what if you're using Drupal's native 'Image' field type?

In this case, you'll actually have to use a slightly different syntax, as the one above only works for Media field types. If you're looking to pull a file URI for an Image field in a custom block template in Drupal 8, you'll need to use the following syntax instead:

{% if content.field_custom_image|render is not empty %}
  {{ file_url(content.field_custom_image.0['#item'].entity.uri.value) }}
{% endif%}