Sonata Media Bundle : acces media url

But if you do not want to render the media right there and just store the url in a variable, you need to ask the media provider for the public url. This was my case, that I needed to pass the url to another template. I did it creating a custom function in my Twig Extension (see here: http://symfony.com/doc/current/cookbook/templating/twig_extension.html).

Provided that you have the container available in your extension service with $this->container, you can do like this:

public function getMediaPublicUrl($media, $format)
{
    $provider = $this->container->get($media->getProviderName());

    return $provider->generatePublicUrl($media, $format);
}

Register the function in the extension:

public function getFunctions() {
     ....
    'media_public_url' => new \Twig_Function_Method($this, 'getMediaPublicUrl'),
     ....
    );
}

And call your new helper form your template:

{% set img_url = media_public_url(media, 'small') %}

for instance

regards


You have to use the path media helper:

{% path media, 'small' %}

In the above code, media is an instance of the media entity, and small is the chosen format.

http://sonata-project.org/bundles/media/master/doc/reference/helpers.html#twig-usage


@javigzz's is perfect in case of default context. I used custom context, so had to handle $format first taking into account context name:

$provider = $this->container->get($media->getProviderName());
$format = $provider->getFormatName($media, $format);
$url = $provider->generatePublicUrl($media, $format);

Additional Note

Since injecting container is not the best practice, it is better to get provider from the provider pool:

class Foo {
    public function __construct(Sonata\MediaBundle\Provider\Pool $pool) {
        $this->pool = $pool;
    }

    public function getUrl($media, $format) {
        $provider = $this->pool->getProvider($media->getProviderName());
        $format = $provider->getFormatName($media, $format);
        $url = $provider->generatePublicUrl($media, $format);

        return $url;
    }
}