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:
public/images/
and reference them directlyNumber 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.
The following should do the trick:
.button.checkable { background-image: url(image_path('tick.png')); }
Rails in fact provides a bunch of helpers to reference the assets:
image-url('asset_name') audio-path('asset_name')
In general
[asset_type]-url('asset_name') #Becomes url('assets/asset_name') [asset_type]-path('asset_name') #Becomes 'assets/asset_name'
asset_type may be one of the following: image, font, video, audio, javascript, stylesheet
sass-rails gem defines Sass functions that can be used from Sass, without ERB processing. https://github.com/rails/sass-rails
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With