How to use absolute path in twig functions

rkmax picture rkmax · Jun 11, 2013 · Viewed 101.3k times · Source

I have an application with Symfony2 (2.2). When I want to send a mail, I'm having trouble with the paths, which are all relative paths and obviously aren't working inside emails

for rendering the paths I'm using:

<a href="{{ path('route_name', {'param' : value}) }}">A link</a>

and for assets:

<img src="{{ asset('bundle/myname/img/image.gif') }}" alt="Title"/>

The previous examples work fine but the paths are relative therefore I need to append the domain. I can do something like:

<a href="http://domain.com{{ path('route_name', {'param' => param1}) }}">A link</a>

but this is not the best solution for my problem, as I have different domains.

Update

I found the solution for paths with the url function but I still need a solution for assets.

Answer

Neto Buenrostro picture Neto Buenrostro · Sep 24, 2015

Symfony 2.7 has a new absolute_url which can be used to generate the absolute url. http://symfony.com/blog/new-in-symfony-2-7-the-new-asset-component#template-function-changes

It will work on those both cases or a path string:

<a href="{{ absolute_url(path('route_name', {'param' : value})) }}">A link</a>

and for assets:

<img src="{{ absolute_url(asset('bundle/myname/img/image.gif')) }}" alt="Title"/>

Or for any string path

<img src="{{ absolute_url('my/absolute/path') }}" alt="Title"/>

on those tree cases you will end up with an absolute URL like

http://www.example.com/my/absolute/path