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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think twig functions are not recognized in a javascript file. I get this error: Uncaught SyntaxError: Unexpected token {
Hey it actually worked. I had to put the code in my script block in my twig template. Thank You!!
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);

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.