Homunculus Reticulli
Homunculus Reticulli

Reputation: 68376

Passing an image filename to JavaScript

I am developing a Rails v4.2 website.

I have a JavaScript object that takes the name of an image file as a property:

var obj = new objects.Factory.MyObject({
    title: 'Sir',
    education: 'Phd',
    icon: './profile.png'
  });

I placed my images in "app/assets/images", however when I load the page, I see a 404 error when trying to retrieve the image.

I tried using image_tag which obviously did not work in Javascript. How may I correctly specify the path of an image in a Javascript code section of a Rails page?

Upvotes: 0

Views: 73

Answers (1)

ipatch
ipatch

Reputation: 4033

I would rename your JavaScript file by appending a .erb to the end of the extension, and then load your assets/images with the following line in your JavaScript file:

<%= asset_path('profile.png') %>

Upvotes: 2

Related Questions