chriseppstein/compass — Issue #673: Expose `sprite-names` as a function
Author: heygrady
Created: 2012-01-12 02:29:21+00:00
State: open

It is useful to obtain a list of sprite names from the sprite map in order to create your own custom stripe classes.

```ruby
module Sass::Script::Functions
def sprite_names(path)
assert_type path, :String
importer = ::Compass::SpriteImporter.new(:uri => path.value, :options => {})

Sass::Script::List.new(importer.sprite_names.map{|s| Sass::Script::String.new(s)}, :space)
end

declare :sprite_names, :args => [:path]
end
```

For my current project I was working with mobile and wanted to generate a sprite-map for retina displays and for normal displays using a media query. Essentially I needed to created two sprite maps and then change which one was used depending on the `device-pixel-ratio`.

```css
$sprites: sprite-map("sprites/*.png");
$retina-sprites: sprite-map("retina-sprites/*.png");

@mixin sprite-classes($size: normal) {
$sprite-names: sprite-names("sprites/*.png");
$map: true;
$background-size: false;

// change the sprite-map based on the size
@if $size == retina {
$map: $retina-sprites;
$background-size: true;
} @else {
$map: $sprites;
}

.sprite-map {
background-image: $map;
background-repeat: no-repeat;

// determine the background-size property based on the width of the sprite image
@if $background-size {
$width: 0px;
@each $sprite-name in $sprite-names {
$tmp-width: image-width(sprite-file($map, $sprite-name));
@if $tmp-width > $width {
$width: $tmp-width;
}
}
@include background-size($width/2 auto);
}
}

// create a class for each sprite in the sprite-map
@each $sprite-name in $sprite-names {
$full-sprite-name: "sprite-#{$sprite-name}";
.#{$full-sprite-name} {
@extend .sprite-map;
@include sprite($map, $sprite-name);
}
.#{$full-sprite-name}-with-dimensions {
@extend .sprite-map;
@include sprite-background-position($sprites, $sprite-name); // background-position should come from the original sprite
@if $background-size {
height: image-height(sprite-file($sprites, $sprite-name));
width: image-width(sprite-file($sprites, $sprite-name));
} @else {
@include sprite-dimensions($map, $sprite-name);
}
}
}
}

// Styles for desktop and large screen
@include sprite-classes();

// iPhone 4, Opera Mobile 11 and other high pixel ratio devices
@media
only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (min--moz-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5) {
// Styles
@include sprite-classes(retina);
}
```