Getting a list of files in sass/compass

旧街凉风 提交于 2019-12-20 11:01:28

问题


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); }

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?


回答1:


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

Then, you can include this file from your compass configuration file (say, "config.rb"):

require File.join(File.dirname(__FILE__), 'list-files.rb')

And access it in your SASS stylesheet just like you want to:

@each $clazz in listFiles("images/*") {
  .#{$clazz} {
    background-image: url('#{$clazz}.png');
  }
}

You can then compile using compass compile -c config.rb, as normal.



来源:https://stackoverflow.com/questions/10314907/getting-a-list-of-files-in-sass-compass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!