4
Oct.2020
Drupal 10: How to get a Drupal image style URL from a media field in a twig template
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 %}
Comments