1时如何使用Sass中的参考图像

1时如何使用Sass中的参考图像

本文介绍了在使用Rails 3.1时如何使用Sass中的参考图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails 3.1项目,资产管道运行良好。问题是,我需要在我的Sass中引用图像,但Rails计算图像URL。 (这在生产中尤其重要,Rails将图像的Git哈希值附加到其文件名以清除缓存。)



例如,在 app / assets / stylesheets / todos.css.scss

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



当我部署(或运行 rake assets:precompile ),文件 app / assets / images / tick.png 移动到 public / assets / tick-48fe85c0a.png 或类似的东西。这打破了CSS。 提出了两个建议:


  1. 不要使用图片的资源管道,而是将它们放在 public / images /

数字1当然是一种可能性,虽然它意味着我不会缓存清除我的图像。因为我使用的是Sass而不是ERB来处理文件。

解决方案
  .button.checkable {background-image:url(image_path('tick.png')); } 

Rails实际上提供了一堆参考资产的帮助:

  image-url('asset_name')
audio-path('asset_name')
pre>

一般来说

  [asset_type] -url ')#Becomes url('assets / asset_name')
[asset_type] -path('asset_name')#becomes'assets / asset_name'

asset_type可能是以下其中一种:image,font,video,audio,javascript,stylesheet


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.

解决方案

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

这篇关于在使用Rails 3.1时如何使用Sass中的参考图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:58