Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate asset URL from within a service?

Tags:

php

symfony

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?

like image 873
Nicolas Laplante Avatar asked Feb 07 '12 16:02

Nicolas Laplante


2 Answers

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.

like image 89
Cerad Avatar answered Oct 24 '22 05:10

Cerad


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');
like image 35
Thomas Landauer Avatar answered Oct 24 '22 04:10

Thomas Landauer