Drupal - How to get an image URL from a field in a twig template

An image field stores the file id in target_id. You can access the file id with:

{{ node.field_main_image.target_id }}

There is a second property in the image field. It is for the referenced entity, in this case the file object. This is not visible in the debug output, because it is computed:

{{ node.field_main_image.entity }}

In the file object you find the field uri

{{ node.field_main_image.entity.uri.value }}

which you can use the get the url of the original image

{{ file_url(node.field_main_image.entity.uri.value) }}

or the url of an image style

{{ node.field_main_image.entity.uri.value | image_style('thumbnail') }}

The filter for the image style is part of this module which you have to install:

https://www.drupal.org/project/twig_tweak


You cannot get image url directly in twig template as image fields have just image file id. Every image in Drupal 8 is a file entity.

You can try in template_preprocess_node():

$image_file_id = $variables['node']->field_image[0]->target_id;
$image_file = \Drupal\file\Entity\File::load($image_file_id);
$uri = $image_file->uri->value;
$variables['url']=file_create_url($uri);

Tags:

Media

Theming