Вопрос

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.

Это было полезно?

Решение

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!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top