Symfony2 Assetic get asset urls from inside controller, not template
Asked Answered
A

1

14

I want to include the url to one of the assets in my bundle in the controller, not in the template.

More specifically, but not very important: I make a HighChart chart using obHighChartsBundle, and I have to plot some special icons in some points of the graph I am producing. Therefore I need the url to the icon, which is in my bundle's asset folder.

Is it possible to call some kind of asset manager from the controller and get the correct url to this asset?

Abaft answered 26/3, 2013 at 18:21 Comment(0)
N
39

You can call ($packageName is optional):

$this->container->get('assets.packages')->getUrl($path, $packageName);

For older Symfony versions service is called templating.helper.assets, so you use:

$this->container->get('templating.helper.assets')->getUrl($path, $packageName);

It's used the same way as twig function (in fact this is called in the twig function).

Newfoundland answered 26/3, 2013 at 22:21 Comment(12)
do I need a use statement for including twig somehow?Abaft
I'm not sure, what you are asking. You don't need twig in order for this to work.Newfoundland
I was thinking assetic but wrote twig ;) but I got it working.Abaft
How do you get a full url out of this?Baseler
Function getUrl has optional 3rd argument absolute (boolean).Newfoundland
Any other solutions? I don't want to couple my code with Templating component.Phebe
I suppose you could look into source of Templating component and copy the code from there. But you'd need to implement whole bundle/package registration/lookup code. That feels like inventing the wheel. Twig is not necessary for Templating, so I'm not sure why you don't want to use it, unless you're writing console app, in which case this solution won't work anyway.Newfoundland
This solution doesn't use Assetic, does it? It uses the assets helper of Twig, which is not the same thing.Condor
Assetic and Twig are not required. AssetsHelper is part of the Templating component, which has no dependecies (other than php itself).Newfoundland
As of Symfony3: $this->get('assets.packages')->getUrl($path)Hyperbolize
Not working for me. Using Symfony 2.6. In my controller, I am doing this: $test = $this->container->get('templating.helper.assets')->getUrl("@MyBundle/Resources/public/images/navbar_logo.jpg", null);, and all I get in $test is /@MyBundle/Resources/public/images/navbar_logo.jpg, which is basically the path I passed as parameter, prefixed by /. And it isn't working. What I am doing wrong?Biolysis
@Biolysis Bundle notation is evaluated by Assetic, not by the asset helper of Templating component this solution uses. You could instead use something like $this->container->get('templating.helper.assets')->getUrl('images/navbar_logo.jpg', 'bundles/my/Resources/public'). I don't have environment set up to test this, but hopefully you get the idea.Newfoundland

© 2022 - 2024 — McMap. All rights reserved.