0

How to generate dynamic variables in SASS?
I have array/list with colors:

$colors: (
  1: 'black',
  2: 'red',
  3: 'yellow'
);

And now, I also generate dynamic classes:

@each $i, $color in $colors {
  .bg-color-#{$i} {
    background-color: $color;
  }

  .text-color-#{$i} {
    color: $i;
  }
}

Now, I would like have just variables, like this:

$color-1: 'black';
$color-2: 'red';
// etc.

And in future using like this:

.some-class {
    color: $color-2;
}

So, my loop should be generate dynamic variables based on array/list.

kicaj
  • 2,881
  • 5
  • 42
  • 68
  • 1
    Does this answer your question? [Creating or referencing variables dynamically in Sass](https://stackoverflow.com/questions/8533432/creating-or-referencing-variables-dynamically-in-sass) – dantheman Jun 12 '21 at 13:36
  • @dantheman No, a little other – kicaj Jun 15 '21 at 20:28

1 Answers1

0

Fast Result:

/* Colors */
$colors: 'black', 'red', 'yellow';
@each $color in $colors {
    .color-#{$color} {
        color: $color;
    }
}

or

/* Step 1: styles.scss
/// ************************
/// @example
///  @include generate-color();
/// @return
///   .color-black { color: "black"; }
///   .color-red {color: "red"; }
///   .color-yellow {color: "yellow"; }
*/
@mixin generate-color() {
    $colors: 'black', 'red', 'yellow';
    @each $color in $colors {
        .color-#{$color} {
            color: $color;
        }
    }
}

/* Step 2: */
@include generate-color();

/* Step 3: Return ex. styles.css: */
.color-black {
  color: "black";
}

.color-red {
  color: "red";
}

.color-yellow {
  color: "yellow";
}
asbelar
  • 29
  • 1
  • 5
  • No tiene sentido generar las variables de forma dinamica, pero te recomiendo que aprendas a usar estructura de archivos, estare al tanto de la respuesta de otra persona. – asbelar Jun 16 '21 at 18:25