Home > database >  How to interpolate a SCSS variable in a 'variable'?
How to interpolate a SCSS variable in a 'variable'?

Time:01-02

I need to see if there is a way to parse out variables that are effectively, dynamically generated.

I have a list of 'color' definitions from a variables.scss file in my application:

$colorsList: "primary" "success" "info" "warning" "danger" "inverse";

I then have a number of variables that map to various colors:

$primary-color: #558bc3 !default;
$success-color: #259d2c !default;
$info-color: rgba(43, 169, 251, 0.39) !default;
$warning-color:              #FAAA00 !default;
$danger-color: #c82e2d !default;
$inverse-color: #000;

I am trying to create an SCSS page that will effectively create some generated color blocks/css rules:

@each $color in $colorsList {

    $col: "$color-#{$color}";
    $bgcol: "$color-#{$color}";

    .bg-#{$color} {
        background-color: "#{$bgcol}";
    }
    .color-#{$color} {
        color: "#{$col}";
    }
}

This results in the following output:

.bg-primary {
  background-color: "$color-primary"; }

.color-primary {
  color: "$color-primary"; }

.bg-success {
  background-color: "$color-success"; }

Essentially, what I would like to do - is have those variables in the output parsed to the variable values: $color-success gets changed with #259d2c, and so forth.

Is there a way to do this? Or maybe some workaround?

CodePudding user response:

No, what you are trying is not possible, at least so for. A SCSS variable will be interpreted only once, as you can read on the official documentation:

Sass variables are simple: you assign a value to a name that begins with $, and then you can refer to that name instead of the value itself

So when you call background-color: "#{$bgcol}", $bgcol gets replaced by its value, which is just a string in the eye of SCSS, as any interpolated result:

Interpolation can be used in SassScript to inject SassScript into unquoted strings. This is particularly useful when dynamically generating names (for example, for animations), or when using slash-separated values. Note that interpolation in SassScript always returns an unquoted string.

What you can do that's common in the SCSS world is to map your color names to your colors with the help of a map, like so:

$colorsList: "primary" "success" "info" "warning" "danger" "inverse";
$mapedColorsList: (
  "primary": #558bc3,
  "success": #259d2c,
  "info": rgb(43 169 251 / 39%),
  "warning": #faaa00,
  "danger": #c82e2d,
  "inverse": #000,
);

@each $color in $colorsList {
  .bg-#{$color} {
    background-color: map.get($mapedColorsList, $color);
  }
  .color-#{$color} {
    color: map.get($mapedColorsList, $color);
  }
}
  • Related