4

I'm trying to customize a download-link for a file-field in my entity. In a similar setup, i was able to customize a link-field in the following way:

<a href="{{ node.field_publication_link.uri }}"> Link </a>

So, for the file-field, i tried something similar:

<a href="{{ node.field_publication_file.0.uri }}"> Download </a>

However, there is no such thing as a uri field available. I have a hard time figuring out which fields actually are available for me to use in the template. I found kint to be way too noisy, i had to restrict memory consumption and still have no clue which fields are usable.

Alternatively, i tried to create a custom template for the specific file field, called field--field-publication-file.html.twig. The debug info tells me that it is used for rendering. I had a look at the field that my theme (bootstrap) normally uses and tried to mimick its behavior. Specifically, i wanted to use the field link, which is also used in the bootstrap version. However, this field is always empty when using my version.

What more could i try?

2

After more research, i found the answer by accident on this page. One can refer to the link by using:

<a href="{{ file_url (node.field_publication_file.entity.uri.value) }}"> 
  Download
</a>

The fields that were defined in the bootstrap theme don't seem to be accessible in a sub-theme of bootstrap. I'm sure I could have written a custom preprocessor to do the same thing, but this solution works for me and I don't have to write PHP code.

| improve this answer | |
  • 2
    You can also use node.field_publication_file.entity.url() – Eyal Jan 23 '17 at 20:11
1

You can do it either way, using the file_url available on twig template or you can use file_create_url($file_uri); in the preprocessor, so that your template can easily consume the processed output.

Code at preprocess layer, assuming node as the host entity.

function mymodule_preprocess_node($node) {
   if (!$node->your_file_field_machine_name->isEmpty()) {
     $file_entities = $node->get('your_file_field_machine_name')->referencedEntities();
     if(count($file_entities)) {
        foreach($file_entities as $file_entity) {
            $variables['file_renderable'][] = file_create_url($file_entity->getFileUri());
        }
     }
   }
}

Other way is what you mentioned, use file_url at your twig template.

<a href="{{ file_url (node.field_publication_file.entity.uri.value) }}"> 
  Download
</a>
| improve this answer | |

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.