How to get image url from uri in Drupal 8 template
Asked Answered
M

2

5

I'm trying to create my own image field formatter. I've followed these instructions (http://www.sitepoint.com/creating-custom-field-formatters-drupal-8/) and right now I have a working formatter which basically does nothing but "inherits" and executes default image formatter.

Then I of course have my own template which is also a copy of default image-formatter.html.twig template (found that in core\modules\image\templates).

Now my question is that in template I can print the whole image using Twig syntax {{ image }}. If I use dump(image) I see there's actually image uri like this: public://default_images/Default image for Drupal Ant task.jpg

I'd love to have the actual url instead but right now I have no idea how to get it. Is it even possible? And I would also appreciate if you could explain me shortly why {{ image }} prints image with img tags? It must go through another formatter?

Why I started to do this in a first place was that instead of img tags I'd like to use divs with background image style.

Mezuzah answered 11/11, 2015 at 20:15 Comment(0)
V
13

There is a twig extension file_url you can use for this, for example

{{ file_url(content.field_image['#items'].entity.uri.value) }}
Vassal answered 29/3, 2016 at 21:24 Comment(2)
This was exactly what I was looking for! Worked great. Of course one has to replace field_image with their image field name.Forelli
Same thing work for my node twig , but it fail for views templatesHebert
H
0
<img src={{ file_url(content.field_image['#items'].entity.uri.value) }} class="img-fluid" />

The above one worked from the node template

Humidifier answered 15/2, 2022 at 16:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.