Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 681
i.am.michiel Avatar asked Jan 10 '12 22:01

i.am.michiel


3 Answers

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.

like image 99
solarc Avatar answered Oct 15 '22 03:10

solarc


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!

like image 41
smatyas Avatar answered Oct 15 '22 04:10

smatyas


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();
    }
}
like image 29
iamdto Avatar answered Oct 15 '22 02:10

iamdto