How to get the full url for an asset in Controller?
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();
}
}
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
.
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!