6

I have a map in Sass with keys and values

 $colors: (blue: #0081d2, green: #288600, orange: #e57323);

 @each $color, $value in $colors {
    .#{$color} {
        color: $value; 
    }
 }

This works and gives me css classnames with the appropriate values, like:

 .blue{
    color: #0082d1;
 }

What is would like to have is a function that produces sass variables based on the keys in the map.

 $blue:  #0082d1;
 $green: #288600;

I have been breaking my head but can't get it to work.

timmy
  • 468
  • 1
  • 6
  • 21

2 Answers2

2

You could create a function to return the value by the key specified.

Example

$colors: (blue: #0081d2, green: #288600, orange: #e57323);

@function color($color) {
    @return map-get($colors, $color);
}

.bacon {
  color: color(blue);
}

Results in

.bacon {
  color: #0081d2;
}
Colin Bacon
  • 15,436
  • 7
  • 52
  • 72
0

The whole point of a map is to have data structured in a more hierarchical way and not just as a bunch of variables. If you don't want this, define variables instead of a map in the first place.

But I'm guessing what you really want is a way to access map values. Try this:

map-get($colors, blue)
mzgajner
  • 2,250
  • 1
  • 17
  • 14
  • Thank you for you answer. Do you suggest that I take on a different strategy? I want one place where I can put my color palette. And reference it whenever I need to. – timmy Apr 17 '15 at 13:17