In this blog post, we will explore how to get the path of an uploaded file inside a Twig template in Drupal 10, whether the file is of type "File" or "Media". We will demonstrate how to extract just the path to the PDF file in a template, specifically within the node--type--teaser.html.twig template.
Step 1: Set the Field Type as "File"
Make sure the field type is set as "File". In case the field type is set as "Media", refer to the instructions in Step 3.
Step 2: Manage the Teaser Display for File Field Type
Change the format of your file field to "Generic File" from admin/structure/types/manage/YourContentType/display/teaser. In your Twig template (node--type--teaser.html.twig), just print the following code:
{{ file_url(node.field_pdf.entity.uri.value) }}
You will get the path to your file. Note: As mentioned in the discussion, it's uri, not url.
Step 3: Set the Field Type as "Media"
If the field type is set as "Media", you can still get the path to the uploaded file by following these steps:
Step 4: Manage the Teaser Display for Media Field Type
Change the format of your media field to "Rendered entity" from admin/structure/types/manage/YourContentType/display/teaser. In your Twig template (node--type--teaser.html.twig), use the following code:
{{ file_url(node.field_pdf.entity.field_media_file.entity.uri.value) }}
This code will give you the path to your media file. Note that field_media_file should be replaced with the appropriate field name within your media entity.
Alternative Method: Using URL to File Format
If the above solutions don't work for you, you can try changing the file or media field's format to "URL to file" in the Manage Display settings. Then, in your Twig template, render the file field, strip its tags, trim the result, and pass it to file_url like this:
{% set url = file_url(content.field_pdf_file|render|striptags|trim) %}