最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Symfony 2:image paths in javascript file with assetic - Stack Overflow

programmeradmin0浏览0评论

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/bundles/web/app_dev.php/project/1/assets
   /images/linkArrow.png"

my image is under the web/assets file.

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./bundles/web/app_dev.php/project/1/assets
   /images/linkArrow.png"

my image is under the web/assets file.

Share Improve this question asked Apr 16, 2014 at 0:21 AkramAkram 1743 silver badges12 bronze badges 1
  • What does the rendered HTML / JavaScript source look like? – Phil Commented Apr 16, 2014 at 1:40
Add a ment  | 

1 Answer 1

Reset to default 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!

发布评论

评论列表(0)

  1. 暂无评论