user3411864
user3411864

Reputation: 644

How to get the field_image path with Twig in Drupal 8

To make an animated slider, I overwrite a fields view template file in my own template named: views-view-fields--slider.html.twig

Inside that file I have access to a fields array to print out all the fields that are in my content-type slide.

The problem is that I need to get the path of the image file instead of the image itself, because I need the path for CSS background-image styling.

The following doesn't work:

<div class="jumbotron " ref="" style="background-image:url(?????);">
   {{ file_url(fields.field_image.entity.fileuri) }}
</div>

I tried everything I good find on Google:

fields.field_image.entity.uri
fields.field_image.entity.uri.value
fields.field_image.entity.url
fields.field_image.entity.url.value

etc.

Has anyone an idea how it is done in Drupal 8 ?

Upvotes: 1

Views: 9386

Answers (3)

S.Skns
S.Skns

Reputation: 31

Try {{ file_url(row._entity.field_image.entity.uri.value) }}. It works for me.

<div style="background-image:url({{ file_url(row._entity.field_image.entity.uri.value) }});"></div>

Upvotes: 3

James Hou
James Hou

Reputation: 26

I found this module: image_url_formatter, so in View interface, I can use this to formatter my image filed as path.

It works perfect, but if I turned the twig debug on, it wouldn't work, because it will output debug annotation. I don't know how to solved it yet.

I use fields.field_image.content to show the path, I don't konw whether it's rignt.


Solution without extra module:

In your Views:

1.Add your image filed to the Advanced/Relationship

2.Then in the filed section, change to File Group, you can see URI field,add it, and make sure you check "Display the file download URI"

3.Add your new field in the twig template: {{ field.uri.content }}

Done!

Upvotes: 1

Keldus
Keldus

Reputation: 21

Since you are in views-view-unformatted you should already have access individualy to each field of your content type Slide with {{ row.content }} and because of that you have to do:

{{ file_url(row.content.field_image.entity.fileuri) }}

Upvotes: 2

Related Questions