Getting a list of files in sass/compass

compass-sass, sass

Solution

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.

Problem

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?

Original source