How to get the full url for an asset in Controller?

i.am.michiel picture i.am.michiel · Jan 10, 2012 · Viewed 100.3k times · Source

I need to generate some JSON content in controller and I need to get the full URL to an uploaded image situated here : /web/uploads/myimage.jpg.

How can I get the full url of it?

http://www.mywebsite.com/uploads/myimage.jpg

Answer

solarc picture solarc · Jan 11, 2012

You can generate the url from the request object:

$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();

You could make a twig extension that cuts the /web part of your path and uses the request to generate the base url.

see Symfony\Component\Routing\Generator\UrlGenerator::doGenerate for a more solid implementation.

Also, Twig has access to the request from app.request.