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 1:
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
.
Solution 2:
You can use this in Controller:
$this->getRequest()->getUriForPath('/uploads/myimage.jpg');
EDIT : This method also includes the app.php
and app_dev.php
to the url. Meaning this will only work in production when url-rewriting is enabled!
Solution 3:
You can use the templating.helper.assets
service.
First define your assets base URL :
# app/config/config.yml
framework:
templating:
assets_base_url: "http://www.mywebsite.com/"
Then just call the service from within your controller, command or wherever you are :
<?php
// src/Acme/Bundle/DemoBundle/Controller/DemoController.php
namespace Acme\Bundle\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DemoController extends Controller
{
public function indexAction()
{
$myAssetUrl = $this
->get('templating.helper.assets')
->getUrl('bundles/acmedemo/js/main.js', $packageName = null)
;
// $myAssetUrl is "http://www.mywebsite.com/bundles/acmedemo/js/main.js"
return array();
}
}