Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fetch image from the assets/images folder in a rails app

I have been searching and searching for this answer. But I cannot seem to make this work, several hours now. Please please help me.

I'm a webpage of my rails app, I am trying to show an image saved in my assets folder @app/assets/images/rails.png.

I have a javascript file with the following function that constructs html. Inside this function, I'd like to pass the link to the image. This is the code I have currently.

function addToInfoWindow(infoWindowContent)
{

infoWindowString = '<div class="infoWindow">'+
**'<img src="/assets/images/rails.png" />'+**
'<p>'+infoWindowContent+'</p>'+
'<p><a href="http://www.google.com">See here</a></p>'+
'<p><a href="http://www.google.com">Upload a photo</a></p>'+
'</div>';
infoWindow.setContent(infoWindowString);

}

As you can see above in the code the bold part is the problem. I've tried several different combinations of url strings to access that image file but the image does not show up in the html element.

I've looked and looked, tried rails helper functions such as image_url('rails.png'). But I must be putting them in the wrong place. Can someone please help me. Please show me where , what function in the above code I need to add to fetch the image at /assets/images/rails.png so that it's url is placed in the highlighted part above and it shows in my view.

like image 443
banditKing Avatar asked Apr 21 '12 22:04

banditKing


2 Answers

If you want to you use the rails helpers you need to "upgrade" your javascript files to erb.

Just rename them from whatever.js to whatever.js.erb. Now rails will execute all the erb code (stuff between <%= and %>) before delivering the file.

So you can do like this:

<img src="<%= asset_path( 'rails.png' ) %>" />

More information, see 2.2.3.

like image 87
klump Avatar answered Nov 03 '22 00:11

klump


You won't be able to use the rails helpers like image_tag in pure javascript - append .erb and use asset_path (see klump's answer)

like image 31
DanS Avatar answered Nov 03 '22 01:11

DanS