How to reference images in CSS within Rails 4

There's a strange issue with Rails 4 on Heroku. When images are compiled they have hashes added to them, yet the reference to those files from within CSS don't have the proper name adjusted. Here's what I mean. I have a file called logo.png. Yet when it shows up on heroku it is viewed as:

/assets/logo-200a00a193ed5e297bb09ddd96afb953.png

However the CSS still states:

background-image:url("./logo.png");

The result: the image doesn't display. Anybody run into this? How can this be resolved?


Sprockets together with Sass has some nifty helpers you can use to get the job done. Sprockets will only process these helpers if your stylesheet file extensions are either .css.scss or .css.sass .


Image specific helper:

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

Agnostic helper:

background-image: asset-url("logo.png", image)
background-image: asset-url($asset, $asset-type)

Or if you want to embed the image data in the css file:

background-image: asset-data-url("logo.png")

Don't know why, but only thing that worked for me was using asset_path instead of image_path , even though my images are under the assets/images/ directory:

Example:

app/assets/images/mypic.png

In Ruby:

asset_path('mypic.png')

In .scss:

url(asset-path('mypic.png'))

UPDATE:

Figured it out- turns out these asset helpers come from the sass-rails gem (which I had installed in my project).


In Rails 4, you can reference an image located in assets/images/ in your .SCSS files easily like this:

.some-div {
  background-image: url(image-path('pretty-background-image.jpg'));
}

When you launch the application in development mode ( localhost:3000 ), you should see something like:

background-image: url("/assets/pretty-background-image.jpg");

In production mode, your assets will have the cache helper numbers:

background-image: url("/assets/pretty-background-image-8b313354987c309e3cd76eabdb376c1e.jpg");
链接地址: http://www.djcxy.com/p/78012.html

上一篇: Rails 4图像不能在heroku上加载

下一篇: 如何在Rails 4中引用CSS中的图像