How to reference images in CSS within Rails 4

2020-01-23 04:26发布

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?

17条回答
来,给爷笑一个
2楼-- · 2020-01-23 04:30

The hash is because the asset pipeline and server Optimize caching http://guides.rubyonrails.org/asset_pipeline.html

Try something like this:

 background-image: url(image_path('check.png'));

Goodluck

查看更多
The star\"
3楼-- · 2020-01-23 04:34

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")
查看更多
虎瘦雄心在
4楼-- · 2020-01-23 04:35

Referencing the Rails documents we see that there are a few ways to link to images from css. Just go to section 2.3.2.

First, make sure your css file has the .scss extension if it's a sass file.

Next, you can use the ruby method, which is really ugly:

#logo { background: url(<%= asset_data_uri 'logo.png' %>) }

Or you can use the specific form that is nicer:

image-url("rails.png") returns url(/assets/rails.png)
image-path("rails.png") returns "/assets/rails.png"

Lastly, you can use the general form:

asset-url("rails.png") returns url(/assets/rails.png)
asset-path("rails.png") returns "/assets/rails.png"
查看更多
啃猪蹄的小仙女
5楼-- · 2020-01-23 04:37

You can add to your css .erb extension. Ej: style.css.erb

Then you can put:

background: url(<%= asset_path 'logo.png' %>) no-repeat;
查看更多
三岁会撩人
6楼-- · 2020-01-23 04:38

Only this snippet does not work for me:

background-image: url(image_path('transparent_2x2.png'));

But rename stylename.scss to stylename.css.scss helps me.

查看更多
姐就是有狂的资本
7楼-- · 2020-01-23 04:41

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");
查看更多
登录 后发表回答