简体   繁体   English

Symfony 2:带有资源的javascript文件中的图像路径

[英]Symfony 2:image paths in javascript file with assetic

I'm trying to make a path to an image from a js file in my symfony2 project using asset like this: 我正在尝试使用这样的资产从我的symfony2项目中的js文件创建图像的路径:

   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. 您不能在JavaScript文件中使用细枝语法。 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. 另一种干净的方法是为您的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 注意:如果直接在js文件中引用变量,请确保在加载javascript文件之前定义此脚本。

then you can use it in all your JavaScript files Like: 那么您可以在所有JavaScript文件中使用它,例如:

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

Happy coding! 编码愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM