TransWikia.com

Getting the image URL from a field_image on a node

Drupal Answers Asked by Rias on January 2, 2022

So I have this Node:

object(DrupalnodeEntityNode)[1862]
  protected 'values' => 
    array (size=17)
      'vid' => 
        array (size=1)
          'x-default' => string '7' (length=1)
      'langcode' => 
        array (size=1)
          'x-default' => 
            array (size=1)
              0 => 
                array (size=1)
                  'value' => string 'en' (length=2)
      ... (more fields)
      'field_image' => 
        array (size=1)
          'x-default' => 
            array (size=1)
              0 => 
                array (size=5)
                  'target_id' => string '1' (length=1)
                  'alt' => string '' (length=0)
                  'title' => string '' (length=0)
                  'width' => string '150' (length=3)
                  'height' => string '120' (length=3)

Now the field_image has an array with x-default and some basic image data. How do I show the image, or create a link to the image inside the Twig template?

16 Answers

Just noting: use file_uri, not file_url.

{{ node.field_image|file_uri|image_style('content_header') }}

Answered by Will K. on January 2, 2022

This adds a drupal image style and the image alt test

{{ file_url(content.field_featured_image|field_target_entity.field_media_image.entity.uri.value| image_style('featured_image')) }}" alt="{{ content.field_featured_image|field_target_entity.field_media_image.alt }}

Answered by paul cappucci on January 2, 2022

I would highly recommend using the Twig Tweak module to get the URL from an image field in your twig template. Once you have installed the module you can then use various methods for extracting the URL from the image field. The following worked for me:

{{ node.field_main_image.0 | file_url }}

I set the background image of a <div> with the following:

<div style="background-image: url({{ node.field_banner_image.0 | file_url }})">
...
</div>

Make sure to add style for width and height or you won't see if it's working

IF THIS DOES NOT WORK FOR YOU, or if you want to learn all about the other great things twig tweak can do, reference this cheat sheet. This helpful document will save you a ton of time. I wish I knew about it earlier.

Answered by ob1 on January 2, 2022

You can use the url() method that is on the File class as a shortcut so:

{{ file_url(node.field_image.entity.fileuri) }}

can be shortened to:

{{ node.field_image.entity.url }}

This works in preprocess functions but triggers a Twig_Sandbox_SecurityError when called in a twig template.

If you receive Twig_Sandbox_SecurityError you can tell twig to allow url in your settings.php file as mentioned in this Stackoverflow post

See documentation on File::Url() https://api.drupal.org/api/drupal/core%21modules%21file%21src%21Entity%21File.php/function/File%3A%3Aurl/8.6.x

Answered by Kiee on January 2, 2022

None of the above twig solutions worked for me (perhaps those worked for older 8.x versions but not for 8.5 version

{{ file_url(node.field_image['#items'].entity.uri.value) }}

NOTE: should be working for Drupal 8.5+

Answered by GiorgosK on January 2, 2022

To Get image attribute like URI, alt, title etc use the syntax like below template wise

In node twig template

{{node.field_name.entity.fileuri}}

In field twig template

{{content.field_name.entity.fileuri}}

In other field twig template

{{element['#object'].field_name.entity.fileuri}}

Note: Also check twig_tweaks module cheat sheet for detail related to twig related issue.

Answered by Prem Patel on January 2, 2022

This is the way if you want to get the image URL with the associated image style for any image field in a twig template:

First install the Twig Tweak module

Then set the image URI as a variable. With the URI, you can use a twig tweaks pattern to get the path with whatever image style you want. See below:

{% set image_uri = content.field_feature_row_image['#items'].entity.uri.value %}

<img src="{{ image_uri|image_style('image1200x1103') }}"/>

Twig Tweak v2.4+ offers file_url filter to extract file URL from an entity.

<img src="{{ node.field_image|file_url }}"/>

And as of Twig Tweak v2.6 you can use file_uri filter in conjunction with image_style.

<img src="{{ node.field_image|file_uri|image_style('image1200x1103') }}"/>

Answered by Robb Davis on January 2, 2022

I'm always using a helper function

  /**
   * Get the Image URI.
   *
   * @param DrupalCoreEntityEntity $entity
   * @param $fieldName
   * @param bool $imageStyle
   * @return mixed
   */
  public function getImageUri(DrupalCoreEntityEntity $entity, $fieldName, $imageStyle = FALSE) {
    $imageField = $entity->get($fieldName)->getValue();
    if (!empty($imageField[0]['target_id'])) {
      $file = File::load($imageField[0]['target_id']);
      if ($imageStyle) {
        return ImageStyle::load($imageStyle)->buildUrl($file->getFileUri());
      }

      // Original URI.
      return file_create_url($file->getFileUri());
    }
  }

Answered by hugronaphor on January 2, 2022

somewhat related, here is what I used (thanks to all previous answers to get me there) to get an image file URL from a media entity's image field in twig:

{% set media_img_url = file_url(content.field_media_image.0['#item'].entity.uri.value) %}

now I can use this variable in my twig template

{{ media_img_url }}

Answered by bdanin on January 2, 2022

Gosh, it actually took my ages to find out why my resulting URLs didn't work. The all 404'ed. You need to create a derivate first if it doesn't already exist.

So for example when you add an image style later, after the original image was uploaded, then there's no styled image file yet (the image derivate). It needs to be created first.

Replace field_MYIMAGE and MYSTYLE as you need.

$original_image = $node->field_MYIMAGE->entity->getFileUri();
$style = Drupal::entityTypeManager()->getStorage('image_style')->load('MYSTYLE');

$destination = $style->buildUri($original_image);
if (!file_exists($destination)) {
  $style->createDerivative($original_image, $destination);
}

$url = $style->buildUrl($original_image);

I wish this would happen automatically.

Answered by leymannx on January 2, 2022

What ended up working for me in D8 is:

$imageUrl = $node->get('field_image')->entity->uri->value;

Using kint($node->get('field_image')->entity) and looking through the array was very helpful

enter image description here

Then in my twig file I used:

<img class="top-article-image" src="{{ file_url(imageUrl) }}" />

Answered by crobicha on January 2, 2022

If someone needed a styled image:

$styled_image_url = ImageStyle::load('large')->buildUrl($node->field_image->entity->getFileUri());

Answered by VladimirM on January 2, 2022

Here is an update version of for this answer after 8.0.x. This base on @joelpittet comment.

{{ file_url(node.field_image.entity.fileuri) }}

Answered by itsdarrylnorris on January 2, 2022

you can get the url directly by using field_image.entity.url

Answered by Adrian Kremer on January 2, 2022

So I've found out the answer with the help of Clive.

Getting the image URI in a template file is done using node.field_image.0.entity.uri.value. Provide a Twig extension for file_create_url(), closed as fixed on January, 2015, made possible to use file_url() in a template file.

{{ file_url(node.field_image.0.entity.uri.value) }}

Answered by Rias on January 2, 2022

I don't know about Twig, but you get the file URI with $node->field_image->entity->getFileUri() in PHP, and the you need to call file_create_url() on that:

file_create_url($node->field_image->entity->getFileUri())

I don't know if that is possible in twig. If it's not possible, you can always calculate it in preprocess and add as a new variable.

Answered by Berdir on January 2, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP