1

I'm trying to make a path to an image from a js file in my symfony2 project using asset like this:

   var arr = $('<img src="{{ asset("assets/images/linkArrow.png")}}">').css({
    position: 'absolute',
    ...
    });

but I'm having the following error

    "NetworkError: 404 Not Found - mywebsite.com/bundles/web/app_dev.php/project/1/assets
   /images/linkArrow.png"

my image is under the web/assets file.

1
  • What does the rendered HTML / JavaScript source look like? Commented Apr 16, 2014 at 1:40

1 Answer 1

10

You cannot use twig syntax in your JavaScript file. If you can put your script in your template file it would work then. another clean way would be define a assets base path variable for your javascript. For example, to solve your problem you can add following code in your layout template:

<script>
    var assetsBaseDir = "{{ asset('assets/') }}"
</script>

NB: Make sure you define this script before loading the javascript file, if you are referencing the variable directly in your js file

then you can use it in all your JavaScript files Like:

var arr = $('<img src="' + assetsBaseDir + 'images/linkArrow.png'+ '">').css({
    position: 'absolute',
    ...
});

Happy coding!

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

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.