4 Oct.2020

Drupal 10: How to get a Drupal image style URL from a media field in a twig template

drupal entities

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 %}
    <div class="media">
      <img alt="{{ image_alt }}" title="{{ image_title }}" src="{{ image_url }}" class="contact-info__image"/>
    </div>
  {% endif %}
{% endif %}

In case, if an image displays as a thumbnail:

{% if content.field_media|field_value is not empty %}
  {% set image_url = file_url(content.field_media['#object'].field_image.entity.uri.value|image_style('inline_media')) %}
  {% set image_alt = content.field_media['#object'].field_image.alt %}
  {% set image_title = content.field_media['#object'].field_image.title %}
  {% if image_url %}
    <div class="media">
      <img alt="{{ image_alt }}" title="{{ image_title }}" src="{{ image_url }}" class="contact-info__image"/>
    </div>
  {% endif %}
{% endif %}

Ruslan Piskarov

Ukraine
PHP/WEB Developer / Drupal Expert. More than 11 years of experience delivering Drupal based General Purpose solutions for different sectors such as Job Boards, Product Portfolios, Geo Coding, Real Estate solutions, E-Commerce, Classifieds, Corporate and online Magazines/Newspapers.