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

2

28

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?

Vaientina answered 11/9, 2011 at 20:30 Comment(2)
Can you give an example usage of this in CSS and HTML?Kamila
you should use background-image: image-url("rails.png"). not relevant to this question though...Clavus
T
51

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.

Thessalonians answered 12/9, 2011 at 5:16 Comment(1)
The answer, in short is, use erb.Vaientina
S
2

In Rails 4, instead of using a js.erb view I recommend that you stick to the asset pipeline, and pass the URL to it with a variable instead using gon or some other technique discussed at: Ruby on Rails - Send JavaScript variable from controller to external Javascript asset file

With gon:

app/views/layouts/application.html.erb:

<head>
  <meta charset="utf-8"/>
  <%= include_gon %>

app/controllers/application_controller.rb:

before_filter { gon.path = asset_path 'image.png' }

app/assets/javascripts/file.js.coffee:

alert gon.path

This method is faster because file is precompiled only once at startup, gets served by the server instead of through Rails, and on the same HTTP request as the rest of the Js.

Sheliasheline answered 11/11, 2014 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.