40

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?

  • Don't have time to check but maybe as simple as url(node.field_image.0.entity.uri) (relevant issue) – Clive Nov 19 '14 at 11:58
  • @Clive I tried this and gives me this error: Recoverable fatal error: Object of class Drupal\Core\Field\FieldItemList could not be converted to string so I tried it with this: url(node.field_image.0.entity.uri.value)but then it just tells me this: Twig_Error_Runtime: An exception has been thrown during the rendering of a template ("Route "public://image.png" does not exist.") – Rias Nov 19 '14 at 13:58
  • Errr...I would guess it needs to be done in a preprocess hook then, unless there's a Twig helper function to convert FieldItemLists into a string representation (which I can't find) – Clive Nov 19 '14 at 13:59
  • Oh I see, url() wants a route. How about url_from_path(node.field_image.0.entity.uri.value)? – Clive Nov 19 '14 at 14:00
  • Hmm url_from_path() seems to generate this: http://mywebsite.local/public%3A//image.png so it seems to be urlencoding and appending the exact value to the url – Rias Nov 19 '14 at 14:12

14 Answers 14

43

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) }}
  • 2
    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... – Philipp Michael Aug 8 '16 at 10:35
  • 2
    ... image styles are now available in Twig Tweak - drupal.org/project/twig_tweak – 4k4 Mar 18 '17 at 14:57
29

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.

  • 1
    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) }} – joelpittet Nov 20 '14 at 19:24
21

If someone needed a styled image:

$styled_image_url = ImageStyle::load('large')->buildUrl($node->field_image->entity->getFileUri());
  • 3
    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 Oct 12 '16 at 23:28
  • 2
    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 – mikeDOTexe Oct 18 '16 at 16:27
7

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

5

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) }}" />
  • what if there is not image inserted and we have set default value. – amol Feb 10 '17 at 5:40
2

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

2

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

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

1

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());
    }
  }
0

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.

0

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

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

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.

-3

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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.