Nicolas Laplante
Nicolas Laplante

Reputation: 209

How to generate asset URL from within a service?

I'm using Symfony 2 and I want to generate the absolute url to an asset from a service class, not a template. I'd like the same thing that

{{ asset('/path/to/my/asset') }}

would return in a template.

Is this possible?

Upvotes: 9

Views: 6018

Answers (2)

Thomas Landauer
Thomas Landauer

Reputation: 8355

Here's a simple and clean way for Symfony 2.8:

services.yml:

arguments:
    assets: "@templating.helper.assets"

In the service:

protected $assets;

public function __construct($assets)
{
    $this->assets = $assets;
}

Then you can use it in any function of the service like this:

$this->assets->getUrl('myurl');

Upvotes: 6

Cerad
Cerad

Reputation: 48865

Take a look at: Symfony/Bundle/TwigBundle/Extension/AssetExtension

public function getAssetUrl($path, $packageName = null)
{
    return $this->container->get('templating.helper.assets')->getUrl($path, $packageName);
}

Basically, inject templating.helper.assets into your service then call getUrl.

Upvotes: 15

Related Questions