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?
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With