4

Is it possible to serve a file in a Twig template? I need to get a file (asset) from a global setting, and serve it at a particular URL.

This code is close, but it seems that source() is the wrong method to get the file contents with.

{% header "Content-type: application/pdf" %}
{% header "Content-Disposition: inline" %}

{% set filePath = [craft.config.environmentVariables.assetPath, filesImages.deliveryCalendar[0].filename]|join('') %}

{{ source( filePath ) }}

The variable filePath contains the correct system path to the file (/var/www/site.com/html/assets/file.pdf), but source() is clearly for templates and not files.

How can the contents of a file be streamed out to the browser?

  • For those interested: Brad's answer is very valid but I couldn't get controller actions to work. Instead I added a Twig extension modelled very closely after dbug(), then used the above template file with my custom extension {{ dlfile(cal.pdfFile[0].id) }} to dump the contents of the PDF. gist.github.com/emcniece/bcf3d902e5469613fb1c – emc Dec 1 '15 at 5:56
3

You'd need to make a simple Craft plugin that added a Twig filter/function that wrapped PHP's file_get_contents to grab the file contents, but at that point, you might as well just make it a wrapper for craft()->request->sendFile().

2

In March, I released a Digital Download plugin which makes this process extremely simple...

<a href="{{ craft.digitalDownload.url(asset) }}">{{ asset.title }}</a>

View the complete documentation to read more about how it works.

  • Thanks for contributing to the community! I definitely spent more than $30 worth of time trying to figure this out :D – emc Jul 17 '16 at 16:36

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.