Hendrix
Hendrix

Reputation: 179

Sass variable not working in for

I have a problem converting a string to a variable, because it generates an error

I have tried in several ways to convert this variable into a line, in order to obtain the colors in the classes

c-gray + $i

SASS

$c-gray1: #666;
$c-gray2: #979797;
$c-gray3: #4c4c4c;
$c-gray4: #b9c6d1;
$c-gray5: #f7f8f9;

@for $i from 1 through 5 {

  $colorsGrays: c-gray + $i;
  $count: 1;
  @each $color in $colorsGrays {
    .gBgcGray#{$i} {
      background-color: $color;
    }

    .gCGray#{$i} {
      color: $color;
    }

    .g-bc--gray#{$i} {
      border-color: $color;
    }

    $count: $count + 1;
  }
}

OUTPUT:

.gBgcGray1 {
  background-color: c-gray1;
}

.gCGray1 {
  color: c-gray1;
}

.g-bc--gray1 {
  border-color: c-gray1;
}

.gBgcGray2 {
  background-color: c-gray2;
}

.gCGray2 {
  color: c-gray2;
}

.g-bc--gray2 {
  border-color: c-gray2;
}

.gBgcGray3 {
  background-color: c-gray3;
}

.gCGray3 {
  color: c-gray3;
}

.g-bc--gray3 {
  border-color: c-gray3;
}

.gBgcGray4 {
  background-color: c-gray4;
}

.gCGray4 {
  color: c-gray4;
}

.g-bc--gray4 {
  border-color: c-gray4;
}

.gBgcGray5 {
  background-color: c-gray5;
}

.gCGray5 {
  color: c-gray5;
}

.g-bc--gray5 {
  border-color: c-gray5;
}

TEST: https://sass.js.org/

There is some way to generate a code with the correct one to get the values in the SASS and the OUTPUT

Upvotes: 0

Views: 56

Answers (1)

Flying
Flying

Reputation: 4570

Sass can't resolve variables in this way, but you can use either list or map and resolve colors:

Using list:

$c-gray: #666 #979797 #4c4c4c #b9c6d1 #f7f8f9;
@for $i from 1 through 5 {
  $colorsGrays: nth($c-gray, $i);
}

Using map:

$colors: (
  c-gray1: #666,
  c-gray2: #979797,
  c-gray3: #4c4c4c,
  c-gray4: #b9c6d1,
  c-gray5: #f7f8f9,
);

@for $i from 1 through 5 {
  $colorsGrays: map-get($colors, c-gray + $i);
}

Moreover in these cases you can use @each $colorGrays in $colors instead of @for

Upvotes: 1

Related Questions