Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony and assets usage at runtime with Javascript

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:

  1. Maybe exists something like the FOSJsRoutingBundle, but I really ignore it!
  2. A dirty way could be to generate the path for a known resource, e.g. the 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!
like image 693
JeanValjean Avatar asked Feb 25 '26 20:02

JeanValjean


2 Answers

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>
like image 86
Wouter J Avatar answered Feb 28 '26 11:02

Wouter J


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.

like image 41
David Frank Avatar answered Feb 28 '26 09:02

David Frank