Skip to main content
  • Guides & Documentation

Knowledgebase

Featured articles, how-to guides and quick tips.

Get Media Image URL in Paragraphs 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 Paragraphs template using Twig, simply use the following syntax, replacing the field name with your custom Media field machine name:

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

Of course, this code works really well for Media fields.

But Media fields aren't the same as Image fields in Drupal 8, so if your field is actually using the Image field type, rather than a Media (entity reference) field, then you'll need to use the following syntax instead:

{{ file_url(paragraph.field_custom_image.entity.uri.value) }}

But what if you need to access the alt value for the image?

That's easy, too. You should use the following syntax, switching out the bold for the machine name of your image field:

{{ content.field_custom_image['#items'].alt }}

And the title value for the field? Not a problem, just use this:

{{ content.field_custom_image['#items'].title }}