문제

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