Search code examples
symfonyassetic

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


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


Solution

  • 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.