Alex Rivera | Logout

How do I use reference images in Sass when using Rails 3.1?

Asked 2011-06-18T01:36:38.217
51

I have a Rails 3.1 project with the asset pipeline working great. The problem is that I need to reference images in my Sass, but Rails calculates image URLs. (This is particularly important in production, where Rails appends the Git hash of the image to its filename to bust caches.)

For example, in app/assets/stylesheets/todos.css.scss:

.button.checkable { background-image: url(/assets/tick.png); }

When I deploy (or run rake assets:precompile), the file app/assets/images/tick.png is moved to public/assets/tick-48fe85c0a.png or something similar. This breaks the CSS. This post makes two suggestions:

  1. don't use the asset pipeline for images -- instead put them in public/images/ and reference them directly
  2. use ERB for your CSS and let Rails work out the image URL.

Number 1 is certainly a possibility, though it means I don't get cache-busting on my images. Number 2 is out because I'm using Sass, not ERB to process the files.

Edit
Report

1 Answer

2

For those who are in favor for faster load times for users, may I suggest following Steve Souders tip for loading images in CSS in base64.

asset-data-url('path')

https://github.com/rails/sass-rails#asset-helpers

answered 2012-11-28T23:53:38.810

Your Answer