How to get Media entity image (Entity Reference Field) URL in TWIG theme

Created on 26 February 2017, over 7 years ago
Updated 8 May 2024, about 2 months ago

Apologies if this question has already been asked. However, in my research I found the answers have been for simple image fields which are in default install of Drupal 8. However, in order to have reusable media, I am using Media Entity and associated modules. The problem is I am not able to access image or its URL in TWIG template, where simple image fields work just fine.

While the code below works as expected if field_image is a simple Image type.
<div class="header-title white overlay" style="background-image:url({{content.field_image.0}});">

But the code below doesn't work since field_image2.0 is an Entity reference field.
<div class="header-title white overlay" style="background-image:url({{content.field_image2.0}});">

In case of Entity Reference field, the output is fully escaped and contained in tag. This breaks the structure of my theme. How can I get raw image or URL? I am not a programmer so I don't know how to write preprocessor code or how to construct render arrarys in preprocessors. I just need the url of the source field.

I am attaching configuration images for the Media Bundle I am using and the node configuration in which I'm using the two types of image fields.

Media Bundle configuration [see image 1]
Node configuration [see image 2]
Note, in the second image, 'field_image' is default drupal image type, while 'field_image2' is an entity reference field as configured in the Media bundle above.

I've tried using the following code (gleaned from the internet) to get the URLs but with little success:

$node = $variables['node'];
    $bundle = $node->bundle();

    $hero_image = $node->get('field_image2')->getValue();
    if (!empty($hero_image)) {
      $entity = Media::load($hero_image[0]['target_id']);
      $variables['hero_image'] = ImageStyle::load('large')->buildUrl($entity->field_image->entity->getFileUri());
    }

    if (!$node->field_image2->isEmpty()) {
      $image_media_entity = $node->field_image2->entity;
      $media_mime_type = $image_media_entity->field_mime_type;
      
      $media_banner_image = $image_media_entity;
      
      $variables['banner_image'] = $image_media_entity->url();
      // [
      //   '#type' => $media_banner_image->type,
      //   '#theme' => $media_banner_image->theme,
      //   '#langcode' => $media_mime_type->getLangcode(),
      // ];

      // Caption is formatted text, so we must output a render array that will
      // process the text with the appropriate filter.
      $variables['mime_type'] = [
        '#type' => 'processed_text',
        '#text' => $media_mime_type->value,
        '#format' => $media_mime_type->format,
        '#langcode' => $media_mime_type->getLangcode(),
      ];
    }

Please advice how to get this working. Thanks.

Drupal Configuration

  • Drupal 8.3
  • media_entity_browser-8.x-1.0-beta2
  • media_entity-8.x-1.6
  • media_entity_image-8.x-1.2
  • embed-8.x-1.0-rc3
  • entity-8.x-1.0-beta2
  • inline_entity_form-8.x-1.0-beta1
  • file_entity-8.x-2.0-beta3
  • file-8.2.6
  • field_formatter-8.x-1.0
  • image_raw_formatter-8.x-1.x-dev
  • image_url_formatter-image_url_formatter
💬 Support request
Status

Active

Version

1.2

Component

Miscellaneous

Created by

🇮🇳India hpk

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • First commit to issue fork.
  • 🇺🇦Ukraine seorusus

    In my case I 've got media url here
    media_entity = content.field_hero_background.0['#media']
    then
    image_uri = media_entity.field_media_image.entity.fileuri
    The completed code is

        {% if content.field_hero_background.0['#media'] %}
            {% set media_entity = content.field_hero_background.0['#media'] %}
            {% set image_uri = media_entity.field_media_image.entity.fileuri %}
            <div class="parallax__layer parallax__layer--back" style="background-image: url('{{ file_url(image_uri) }}');">
            </div>
        {% endif %}
    
  • 🇺🇸United States x_v

    And if you want to apply an image style, you can simply add
    |image_style('640x360')

    For example:

    {% set media_entity = content.field_media.0['#media'] %}
    {% set image_uri = media_entity.field_media_image.entity.fileuri|image_style('640x360') %}
    
  • 🇿🇦South Africa kanthan

    I jumped through hoops on this in D10.2.4. It seems that the actual image not in the media entity but is in a referenced file field, which contains references to file entities. To access the URL of the image, you'll need to retrieve the file entity associated with the field and then get the URL from that file entity.

    Here's what finally worked for me. (My image is stored in a field called Feature Image with machine name field_feature_image):

    {#  extract a url from a media field #}
                {% if node.field_feature_image | length %}
                  {# Get the first item from the media field #}
                  {% set media_entity = node.field_feature_image.0. entity %}
                  {# Check if the referenced entity exists and has a field_media_image #}
                  {% if media_entity and media_entity.field_media_image | length %}
                    {# Get the file entity associated with field_media_image #}
                    {% set file_entity = media_entity.field_media_image.0. entity %}
                    {# Get the URL of the image #}
                    {% if file_entity %}
                      {% set image_url = file_entity.uri.value %}
                      <img src="{{ file_url(image_url) }}" alt="" class="img-fluid">
                    {% endif %}
                  {% endif %}
                {% endif %}
  • 🇮🇳India garglalit0

    this will work in drupal 9 too get the image url

    $image = $node->get('field_image_name')->getValue()[0]['target_id'];
    $image = \Drupal::entityTypeManager()->getStorage('file')->load($image)->getFileUri();
    $image_url = \Drupal::service('file_url_generator')->generateAbsoluteString($image);

Production build 0.69.0 2024