7

wondering if it is possible to use an array with Sass as I find my self repeating the following sort of thing:

.donkey
  h2
    background-color= !donkey

.giraffe
  h2
    background-color= !giraffe

.iguana
  h2
    background-color= !iguana
Dr. Frankenstein
  • 4,634
  • 7
  • 33
  • 48

3 Answers3

18

Absolutely.

$animals: "donkey", "giraffe", "iguana"
@foreach $animal in $animals
  .#{$animal}
    h2
      background-color: !#{$animal}
Justin Maxwell
  • 439
  • 3
  • 13
  • Justin is right on this. I've used [Sass lists](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#lists) for fun and profit and can vouch for their usefulness. After reading up on Sass lists, you should also take a look at Sass's list functions, found [here](http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#list-functions). They're almost never helpful, but they can really make your life easier in certain instances! – Ray Brown May 02 '12 at 03:42
1

No, this isn't possible. The best way to do it is to define a mixin:

+animal-h2(!name, !color)
  .#{name} h2
    background-color= !color

Then you can have one line per style, rather than three:

+animal-h2("donkey", !donkey)
+animal-h2("giraffe", !giraffe)
+animal-h2("iguana", !iguana)
Natalie Weizenbaum
  • 5,884
  • 28
  • 22
0

nex3's answer is correct. To get this working with SASS on Rails 3.1 I needed to have the following in a css.scss file:

$donkey: #CC4499;

@mixin animal-h2($name, $color) {
  .#{$name} h2 {
    background-color: $color;
  }
}

@include animal-h2("donkey", $donkey);
@include animal-h2("horse", #000);

Which output:

.donkey h2 {
    background-color: #CC4499;
}

.horse h2 {
    background-color: black;
}
AJP
  • 26,547
  • 23
  • 88
  • 127