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
For Symfony 2.7 and newer
See this answer here.
1st working option
{{ app.request.scheme ~'://' ~ app.request.httpHost ~ asset('bundles/acmedemo/images/search.png') }}
2nd working option - preferred
Just made a quick test with a clean new Symfony copy. There is also another option which combines scheme and httpHost:
{{ app.request.getSchemeAndHttpHost() ~ asset('bundles/acmedemo/images/search.png') }}
{# outputs #}
{# http://localhost/Symfony/web/bundles/acmedemo/css/demo.css #}
From Symfony2 documentation: Absolute URLs for assets were introduced in Symfony 2.5.
If you need absolute URLs for assets, you can set the third argument (or the absolute argument) to true:
Example:
<img src="{{ asset('images/logo.png', absolute=true) }}" alt="Symfony!" />
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
Daniel's answer seems to work fine for now, but please note that generating absolute urls using twig's asset
function is now deprecated:
DEPRECATED - Generating absolute URLs with the Twig asset() function was deprecated in 2.7 and will be removed in 3.0. Please use absolute_url() instead.
Here's the official announcement: http://symfony.com/blog/new-in-symfony-2-7-the-new-asset-component#template-function-changes
You have to use the absolute_url
twig function:
{# Symfony 2.6 #}
{{ asset('logo.png', absolute = true) }}
{# Symfony 2.7 #}
{{ absolute_url(asset('logo.png')) }}
It is interesting to note that it also works with path
function:
{{ absolute_url(path('index')) }}
It's possible to have http://test_site.com and https://production_site.com. Then hardcoding the url is a bad idea. I would suggest this:
{{app.request.scheme ~ '://' ~ app.request.host ~ asset('bundle/myname/img/image.gif')}}
I've used the following advice from the docs https://symfony.com/doc/current/console/request_context.html to get absolute urls in emails:
# config/services.yaml
parameters:
router.request_context.host: 'example.org'
router.request_context.scheme: 'https'