Rails-js中的Asset_path,变量为possible

Rails - Asset_path inside js with variable possible?

本文关键字:变量 possible path 中的 Asset Rails-js      更新时间:2023-09-26

是否可以在asset_path中添加一个定义资产的变量?像

test.js.erb

img_container = function(value){
    var img = "<%= asset_path('" + value + "' %>";
    console.log(img);
}

这会打印

/ + value + 

我知道现在已经很晚了,但我已经多次看到这篇文章,因为我一直遇到这个问题(并诅咒资产管道)。我终于找到了解决方案!

向html标记添加数据属性,并添加asset_path作为其值。然后你可以用jQuery.data()读取它,所以:

<%= image_tag("path/to/your/image.png",
    id: "my_image_id",
    data: {gif_url: asset_path("path/to/your/image.gif"}) %>

在您的javascript中:

 var new_image_path = $("#my_image_id").data("gif-url");  

如果你知道你要处理的值的范围,并且没有一百万个不同的选项,还有另一个选项可以解决这个问题。在javascript对象中声明所有图像文件,该对象将打印到页面源代码中,然后在函数中引用对象值。像这样:

// Array of values for country flag images
var country_flags= {};
country_flags["GB"]='<%= asset_path('GB.jpg') %>';
country_flags["ES"]='<%= asset_path('ES.jpg') %>';

然后:

document.getElementById('img').src = country_flags["GB"];

或者像这样,如果你想从其他变量中提取标志名:

document.getElementById('img').src = country_flags[country_code];