Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Drupal 8 & 9: How to get a Drupal image style URL from a media field in a twig template

Parent Feed: 

Retrieving the image URL from an image field in Drupal 8 and 9 seemed pretty straightforward too. Even the solution for getting the image style URL from a simple image field can be found quite easily. Getting the image URL from a media field can also be looked up easily.

In case, if an image displays as a media with display mode:

{% if content.field_media|field_value is not empty %}
  {% set image_url = file_url(content.field_media[0]['#item'].entity.uri.value|image_style('inline_media')) %}
  {% set image_title = content.field_media[0]['#item'].title %}
  {% set image_alt = content.field_media[0]['#item'].alt %}
  {% if image_url %}
    
  {% endif %}
{% endif %}

In case, if an image displays as a thumbnail:

{% if content.field_media|field_value is not empty %}
  {% set file_url = file_url(content.field_media['#object'].field_image.entity.uri.value|image_style('inline_media')) %}
  {% set file_alt = content.field_media['#object'].field_image.alt %}
  {% set file_title = content.field_media['#object'].field_image.title %}
  {% if image_url %}
    
  {% endif %}
{% endif %}
Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web