How to get an image URL from a field in a twig template
Solutions
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);
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
<article{{ attributes.addClass(classes) }}>
<div>
<img src="{{ file_url(node.field_image.entity.uri.value) }}">
</div>
<div{{ content_attributes.addClass('content') }}>
{{ content|without('field_image') }}
</div>
- {{ file_url(node.field_image.entity.uri.value) }}
By this you can get the image field of node in twig template.
- {{ content|without('field_image') }}
By this you will get the contents without node image field.