Skip to main content
  • Guides & Documentation

Knowledgebase

Featured articles, how-to guides and quick tips.

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

{% if node.field_custom_image.value %}
  {{ file_url(node.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 in your Display Suite template instead:

{{ file_url(node.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:

{{ node.field_custom_image.alt }}

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

{{ node.field_custom_image.title }}

But if you're looping through items, use the following instead:

For the alt value:

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

And the title value:

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

Don't forget to use "node.field_name" rather than " content.field_name" in this instance. Display Suite won't like it if you use "content.field_name" here.