Drupal 8 Twig Template: get relative or absolute path from URI

user2735442 picture user2735442 · Oct 8, 2014 · Viewed 12.7k times · Source

I have in a twig template an image url, like "public://path/to/image.png". I want to get "sites/default/files/path/to/image.png" to use it in the template.

I thought it should work with something like this:

{{ url ('public://path/to/image.png') }}

or

{{ file_uri_scheme ('public://path/to/image.png') }}

But all I get are errors. I know that the second one is a PHP function, but is there any chance to do it with TWIG?

Answer

Philipp Michael picture Philipp Michael · Aug 5, 2016

You can use the twig function file_url to get a relative path:

{{ file_url('public://path/to/image.png') }}

Checkout the documentation under https://www.drupal.org/node/2486991

It accepts a uri and creates a relative path to the file. At least in Drupal 8.1.