Drupal - Get the image URL

The variable node is only preloaded in the node template (and the page template, if the url contains the node). Now if you want to access node fields in a field template you have to look in a different place:

field.html.twig:

{{ file_url(element['#object'].field_image.0.entity.uri.value) }}

element['#object'] is the parent entity in a field template and you can access any field from this entity (in your case the node).

If you want to access raw values from the actual field, it's better to follow the logic of the field twig and access the value inside of the items loop directly from the field item object #item:

{% for item in items %}
  {{ file_url(item.content['#item'].entity.uri.value) }}
{% endfor %}

Edit: Get the url of an image style

Install the module Twig Tweak and you can use the uri to get the url of an image style:

{% for item in items %}
  {{ item.content['#item'].entity.uri.value | image_style('thumbnail') }}
{% endfor %}

Just to mention that if you want to do the same in one of the new custom blocks this works:

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

I use this code in my .theme file:

function THEMENAME_preprocess_node(&$variables) {

  if ($variables['node']->field_image->entity) {
      $variables['image_url'] = $url = entity_load('image_style', 'medium')->buildUrl($variables['node']->field_image->entity->getFileUri());
  }
}

It could be improved. I'm checking for the image field, and loading its url with an image style.

Then in my node--page.html.twig file I have this:

{% if image_url is not empty %}
    <div class="featured-thumb">
        <img src="{{ image_url }}"/>
    </div>
{% endif %}

<div>{{ content.body|without('field_image') }}</div>

Again, that could use some improvement. thanks

Tags:

Files

8