As explained in the official Symfony2 docs, in a Twig template one can link to an asset as follows:
<img src="{{ asset('images/logo.png') }}" alt="My logo" />
which will render the right path to the logo.png resource (it depends on the folder where the Symfony2 app lives).
Well, suppose to use a Javascript code that has to load an image at runtime (e.g. as a result from an autocomplete), how can one achieve in Javascript the same result provided by asset function in Twig?
Some note:
logo.png file <script>var known = {{asset('images/logo.png)')}}</script> and so retrieve the path by a string replace on variable known by replacing string images/logo.png with an empty one. But it is a dirty way!You can just remove the file name from the asset function to get an absolute path to a directory:
<script>
var imgDir = {{ asset('images/') }}
</script>
It is very likely, that the path from your js file to your image remains invariable. This gives you a possibility to use a 'hardcoded' path in your javascript file.
Example:
web
|
|--js
| |
| |--foo.js
|
|--images
| |
| |--pic.jpg
In this case, you can access pic.jpg from foo.js by ../images/pic.jpg
Note, that this solution won't work in your twig view, because in your twig view relative asset urls depend on the route url. This is the reason you need the asset function.
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