4

I've been googling this for long time! I need to show images on some menu hover and mouseout. The code is written in a js file. But the images path needs to be generated. Is there any way to generate image paths using something like this

{{ asset('bundles/mybundle/images/menu_down.png') }}

Can FOSJsRoutingBundle used to generate image paths in js files?

3 Answers 3

13

You could set global JS variables on your actual page:

<script>
    var menuDownUrl = "{{ asset('bundles/mybundle/images/menu_down.png') }}";
</script>

And then set inside your javascript file to call the global variable: window.menuDownUrl

Then creates a dependency inside your javascript file, but allows you to set that image dynamically.

2
  • I think twig functions are not recognized in a javascript file. I get this error: Uncaught SyntaxError: Unexpected token { Mar 16, 2012 at 7:03
  • Hey it actually worked. I had to put the code in my script block in my twig template. Thank You!! Mar 16, 2012 at 7:14
8

You can put an input hidden and set the path of the image.

<input type="hidden" id="img_path" value="{{ asset('images/circle_loading.gif') }}">

After that in jQuery you can use it like this

var img  = "<img src=\'"+ $("#img_path").val() +"\'>";
$("div").html(img);
6

Agree with Nick answer, but he forgot the "quotes" around the {{ asset(...) }}.

So it should be written like this:

 var menuDownUrl = "{{ asset('bundles/mybundle/images/menu_down.png') }}"; 

if you want window.menuDownUrl to work and not output you "undefined"

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.