How can I get the direct URL to a file field in twig? I am able to do this for images, but with a file field, it comes up blank.


{% set media_img_url = file_url(content.field_background_image.0['#item'].entity.uri.value) %}


{% set media_file_url = file_url(content.field_cta_file.0['#item'].entity.uri.value) %}
  • Are you sure both structures are the same like that? And is the second field set to display in the given view mode of the content type? It has to not be hidden from display.
    – Kevin
    Nov 20 '18 at 21:15

#item is as far as I know only added by the image field formatter, so it's unlikely you'll find it in other field types.

Instead you can use the block content entity to get field values, for example:

{{ elements.content['#block_content'].field_file.0.entity.uri.value }}

This works independently of field formatters and as commented by @Kevin also when a field is hidden.

  • So this works, but I get a file path of: public://2018-11/myfile.pdf where does that folder go off of?
    – bb2j3z
    Nov 21 '18 at 14:59
  • This is the raw field value of the uri field, use file_url() to transform it to a URL, like you already did successfully in your question.
    – 4k4
    Nov 21 '18 at 15:06
  • 1
    Thanks that did the trick, {% set media_file_url = file_url(elements.content['#block_content'].field_cta_file.0.entity.uri.value) %} You are a lifesaver!!!
    – bb2j3z
    Nov 21 '18 at 15:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.