I have a simple JavaScript file that has a function to dynamically switch a background image. The JavaScript file is included to the page via Assetic. The script sets a CSS background image property via jQuery.
How can I set the correct URL with Symfony 2 so that the CSS URL always points to the correct image? I know I could just append the JavaScript directly to the template file and set the correct URL in the template file via {{ asset(asset_url) }}, but I’d like to know if there is a solution to set the correct path with an external JavaScript file.
You should use JmikolaJsAssetsHelperBundle. It allows you to expose the AssetsHelper service from Symfony2’s templating component to JavaScript. You can then generate relative and absolute asset URLs.
Example of using a
getUrlasset helper to generate your image’s path.Take a deeper look at the documentation.