URL of images in JavaScript code using Rails 3.1 asset pipeline?

pupeno picture pupeno · Sep 11, 2011 · Viewed 16.4k times · Source

In CSS files, you can get the proper name of an image asset (with the fingerprint) by using:

background-image: url(image-url("rails.png"))

but how do you do the same from a JavaScript file?

Answer

Richard Hulse picture Richard Hulse · Sep 12, 2011

I see you are using the sass helper method.

In standard (non Sass) CSS you do something like this:

.class { background-image: url(<%= asset_path 'image.png' %>) }

The CSS file will need to have erb added to the extensions:

file_name.css.erb

For javascript the same rules apply:

file_name.js.erb

and in the file:

var image_path = '<%= asset_path 'image.png' %>'

The Rails asset pipeline guide is an excellent source of information about how to use these features.