1

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 + 
2
  • Even if you get syntax right, this would not work as you expect. Assuming you are using this with asset pipeline, your .erb template will be processed ONLY ONCE during asset compilation so it cannot work with dynamic values in the browser environment (each precompiled asset has a different timestamp added to the filename). The only way to know the path to the precompiled asset would be to call asset_path helper in server side for every asset. Commented Sep 4, 2014 at 11:59
  • Yeah, I suspected that was the case... I will go with scss instead of adding images with js =) Commented Sep 4, 2014 at 13:51

2 Answers 2

2

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");  
Sign up to request clarification or add additional context in comments.

Comments

1

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.