is it possible to add a variable that defines the asset inside asset_path? Like
test.js.erb
img_container = function(value){
var img = "<%= asset_path('" + value + "' %>";
console.log(img);
}
this prints
/ + value +
is it possible to add a variable that defines the asset inside asset_path? Like
test.js.erb
img_container = function(value){
var img = "<%= asset_path('" + value + "' %>";
console.log(img);
}
this prints
/ + value +
I know it is late in the day, but I have come across this post several times, because I keep encountering this issue (and cursing the asset pipeline). I have finally found a solution!
Add a data attribute to an html tag and add the asset_path as its value. Then you can read it with jQuery.data(), so:
<%= image_tag("path/to/your/image.png",
id: "my_image_id",
data: {gif_url: asset_path("path/to/your/image.gif"}) %>
And in your javascript:
var new_image_path = $("#my_image_id").data("gif-url");
There is another option to solve this, if you know the range of values you're dealing with and it's not a million different options. Declare all of the image files in a javascript object, which prints into the page source code, and then reference the object values in your function. Like this:
// Array of values for country flag images
var country_flags= {};
country_flags["GB"]='<%= asset_path('GB.jpg') %>';
country_flags["ES"]='<%= asset_path('ES.jpg') %>';
And then:
document.getElementById('img').src = country_flags["GB"];
Or like this if you want to pull the flag name from some other variable:
document.getElementById('img').src = country_flags[country_code];