11

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.

George G
  • 7,443
  • 12
  • 45
  • 59
banditKing
  • 9,405
  • 28
  • 100
  • 157

2 Answers2

26

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.

klump
  • 3,259
  • 2
  • 23
  • 26
  • 1
    That worked. Wow. I spent 4 hours trying all kinds of stuff and all along it was just because the file did not have extension!!Thanks a lot indeed for your help – banditKing Apr 21 '12 at 23:27
  • 1
    Its always like that :P Glad I could help. – klump Apr 21 '12 at 23:29
  • 1
    Keep in mind if you're using coffeescript, the extension to use erb is `.js.coffee` not `.js.cofee.erb`. the erb is automatic. I know, it's weird like that. But that's how it works. This bit of info should save people some time. – ahnbizcad Nov 03 '14 at 10:44
3

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)

DanS
  • 17,550
  • 9
  • 53
  • 47