0

Let's say for instance we have the next sass partial file:

//_colors.scss

$foo: red;

And we "use" it on another file:

//test.scss

@use './colors'

.test{
 color: colors.$foo;
}

All good, but what if I would like to use/get the value in a dynamic way within a mixin? something like:

//test.scss

@use './colors'

@mixin getColor($type){
 color: colors[$type]; //JavaScript example, * don't actually work *.
 
 or 

 color: #{colors.{$type}; * don't work neither * 
 //The above returns `color: colors.foo` instead of `color: red` on compilation.
 
 or 

 color: colors.#{$type}; * doesn't work neither *
}

.test{
 @include getColor(foo);
}

Is it possible? thanks for the help!

R2rito
  • 21
  • 2
  • I don't think that is possible, see https://stackoverflow.com/a/8539474/864233 – romellem Sep 28 '22 at 21:26
  • Try "@use '../colors' as *;". Then you dont have to use the colors.$type thing. Just use it as a normal variable – Brad Sep 29 '22 at 02:34

1 Answers1

0

For a color, I really much prefer a function so it can be used on any property (color, background-color, border, box-shadow...)

I usually declare a string equivalent to variable names, then define them inside a map. Finally this map is accessible via a dedicated function.

Something like

//_colors.scss

@use 'sass:map';

$favoriteRed: "favoriteRed";
$favoriteYellow: "favoriteYellow";
$favoriteBlue: "favoriteBlue";

$MyColors: (
    $favoriteRed: #c00,
    favoriteYellow: #fc0,
    $favoriteBlue: #0cf
);

@function my-color($tone: $favoriteRed) {
    @if not map.has-key($MyColors, $tone) {
        @error "unknown `#{$tone}` in MyColors.";
    }
    @else {
        @return map.get($MyColors, $tone);
    }
}

This _colors.scss generates no code at all, it can be imported anywhere at no cost. Then, in a specific style file:

//test.scss

@use './colors' as *;

//inside a mixin
@mixin special-hue-component($tone){
    div.foo {
        span.bar {
            border-color: my-color($tone);
        }
    }
}
 
//or directly
.foobartest {
    color: my-color($favoriteBlue);
}
eradrix
  • 1
  • 1