在sass / compass中获取文件列表 [英] Getting a list of files in sass/compass
问题描述
我正在使用sass和指南针,并且试图为与给定图案匹配的图像创建css类。
预期的/生成的CSS基本上是这样的:
I'm using sass and compass and I am trying to create css classes for images matching a given pattern. The intended/resulting css mostly looks like this:
.class1 { background-image: url(class1.png); }
.class2 { background-image: url(class2.png); }
虽然可以使用罗盘Sprite功能( http://compass-style.org/help/tutorials/spriting/ ),这样做很不方便(因为它将生成新的文件),因为图像本身已经是精灵表了。
While it might be possible to use the compass sprite functionality ( http://compass-style.org/help/tutorials/spriting/ ) it is inconvenient (as it will generate new files) in my case as the images are already spritesheets themselves.
因此能够执行类似的操作
So being able to do something like
@each $clazz in listFiles("images/*") {
.#{$clazz} {
background-image: url('#{$clazz}.png');
}
}
很棒。
是否有或多或少的简便方法?
would be great. Is there a more or less easy way to do so?
推荐答案
您可以通过补充内置的SASS来完成此操作/ Compass函数和您自己的自定义Ruby函数。 (请参见SASS参考此处中标题为添加自定义功能的部分。)只需使用您的自定义代码定义一个Ruby文件(例如, list-files.rb):
You can accomplish this by supplementing the builtin SASS/Compass functions with your own custom Ruby function. (See the section titled "Adding Custom Functions" in the SASS reference here.) Just define a Ruby file (say, "list-files.rb") with your custom code like so:
module Sass::Script::Functions
def listFiles(path)
return Sass::Script::List.new(
Dir.glob(path.value).map! { |x| Sass::Script::String.new(x) },
:comma
)
end
end
然后,您可以从指南针配置文件(例如 config.rb)中包含此文件: / p>
Then, you can include this file from your compass configuration file (say, "config.rb"):
require File.join(File.dirname(__FILE__), 'list-files.rb')
并在SASS样式表中访问它,就像您想要的那样:
And access it in your SASS stylesheet just like you want to:
@each $clazz in listFiles("images/*") {
.#{$clazz} {
background-image: url('#{$clazz}.png');
}
}
然后可以使用进行编译像往常一样,罗盘编译-c config.rb
。
这篇关于在sass / compass中获取文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!