By Rias


2014-11-18 23:13:27 8 Comments

So I have this Node:

object(Drupal\node\Entity\Node)[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?

15 comments

@Kiee 2019-03-11 15:28:59

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

@Berdir 2014-11-19 21:09:43

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.

@joelpittet 2014-11-20 19:24:13

We are trying to get file_create_url() into core but lack of interest has made the issue stale. drupal.org/node/2168231 Though if that got in it should be {{ file_url(node.field_image.entity.fileuri) }}

@GiorgosK 2018-07-31 07:45:28

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

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

@Stef 2019-03-01 10:55:07

I think its bad that these kind of things get deprecated after a while. Upgrading Drupal should keep those working! This works for me in Drupal 8.6, thanks.

@Prem Patel 2018-05-31 18:00:52

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.

@Robb Davis 2018-05-22 20:33:15

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_tweaks 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') }}">

@hugronaphor 2018-05-16 19:53:05

I'm always using a helper function

  /**
   * Get the Image URI.
   *
   * @param \Drupal\Core\Entity\Entity $entity
   * @param $fieldName
   * @param bool $imageStyle
   * @return mixed
   */
  public function getImageUri(\Drupal\Core\Entity\Entity $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());
    }
  }

@bdanin 2018-05-02 21:34:27

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 }}

@leymannx 2018-04-20 11:06:18

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.

@BrynJ 2017-03-01 11:18:35

I had the same issue, so I created a get_image_path() Twig function and added it with a bunch of other useful stuff to my boilerplate Starter module:

https://github.com/brynj-digital/starter

The function accepts the image field and the machine name of an image style, then returns that image path.

It works in lots of contexts - you can pass node.field_name, content.field_name or row._entity.field_name (in the case of a View fields template).

@crobicha 2016-08-05 19:12:05

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) }}" />

@amol 2017-02-10 05:40:34

what if there is not image inserted and we have set default value.

@Drock 2016-05-12 12:21:13

You can do it in two ways!

1) file_create_url(---------) // inside write the path of node

2) file_url(-------) // inside write the path of node

@VladimirM 2016-05-12 11:02:59

If someone needed a styled image:

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

@mikeDOTexe 2016-10-12 23:28:01

This is a great answer. Note that in your .theme or .module file you'll want to add this to the top: use Drupal\image\Entity\ImageStyle;

@mikeDOTexe 2016-10-18 16:27:49

I ran into an issue with https, where Safari won't show the image as it uses the IP instead. You may want to add $relative = file_url_transform_relative($styled_image_url); to ensure it's relative. API here

@darol100 2015-12-22 02:20:47

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) }}

@Philipp Michael 2016-08-08 10:35:13

Please note, that you will get the url of the "unstyled" original image and not the image style specific url (e.g. thumbnail). Aside from VladimirM's answer there is no way to get the correct styled image url in twig. At least currently...

@4k4 2017-03-18 14:57:08

... image styles are now available in Twig Tweak - drupal.org/project/twig_tweak

@Kiee 2019-03-11 15:25:05

The File class has a url() method, so you can simply call entity.url() rather than passing entity.fileuri to file_url()

@Adrian Kremer 2015-01-30 13:37:53

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

@Rias 2014-11-20 15:37:12

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

Getting the image URI in Twig is done using node.field_image.0.entity.uri.value

Getting the full URL for the image can be done using file_create_url(node.field_image.0.entity.uri.value)

Doing this in Twig isn't possible yet but they are working on it -> see here

Related Questions

Sponsored Content

1 Answered Questions

[SOLVED] Render field values in node template

  • 2018-08-17 16:16:46
  • chalo
  • 142 View
  • 0 Score
  • 1 Answer
  • Tags:   8

2 Answered Questions

[SOLVED] How to get height and width of image style?

1 Answered Questions

[SOLVED] Getting a custom block image field URL in the block Twig template

  • 2016-01-22 16:03:53
  • cheesetriple
  • 3916 View
  • 3 Score
  • 1 Answer
  • Tags:   theming 8 images

0 Answered Questions

How to set the image as a background using Url to Image formatter?

1 Answered Questions

[SOLVED] Loop through nested array in Twig

  • 2017-09-21 21:13:12
  • Rick Bergmann
  • 800 View
  • 0 Score
  • 1 Answer
  • Tags:   theming 8

0 Answered Questions

Cannot display image

  • 2017-03-31 11:27:47
  • russ
  • 59 View
  • 1 Score
  • 0 Answer
  • Tags:   theming 8

1 Answered Questions

[SOLVED] How to change the image style used in a field in specific view results?

  • 2016-11-18 17:46:41
  • joekers
  • 281 View
  • 6 Score
  • 1 Answer
  • Tags:   views theming 8

2 Answered Questions

[SOLVED] How do I programmatically add an image while programmatically creating nodes?

0 Answered Questions

Render image from $node - no image style applied

  • 2014-04-14 23:29:28
  • tamasgal
  • 92 View
  • 0 Score
  • 0 Answer
  • Tags:   images

2 Answered Questions

[SOLVED] How can I print a field from a referenced entity in my theme?

  • 2013-04-21 05:55:03
  • Peter Clemence
  • 3063 View
  • 4 Score
  • 2 Answer
  • Tags:   theming entities

Sponsored Content