user3803699 user3803699 - 1 month ago 7
Sass (Sass) Question

Nested Scss @each with variables

Is it possible to create a function inside a nested variable with scss/sass?
I was using this article to help guide me but I did not find anything on whether it would work inside a nested color variable.
Article working-with-lists-and-each-loops-in-sass-with-the-index-and-nth-function

I want to create a function to automate the creation of these variables

$oranges: #af5422;
$oranges2: #FFCA28;
$oranges3: #FFA000;

$fish: (
orange: (
"goldfish-1": $oranges,
"goldfish-2": $oranges2,
"goldfish-3": $oranges3,
)
) !default;

h1 {
color: map-get(map-get($fish, orange), "goldfish-1");
}
h2 {
color: map-get(map-get($fish, orange), "goldfish-2");
}
h3 {
color: map-get(map-get($fish, orange), "goldfish-3");
}


codepen

I am looking to do something like this but I can't figure it out.

$oranges: #af5422 #FFCA28 #FFA000;

$fish: (
orange:
@each $current-color in $oranges {
$i: index($oranges, $current-color);
"goldfish-#{$i}": $current-color,
}
)
) !default;

h1 {
color: map-get(map-get($fish, orange), "goldfish-1");
}
h2 {
color: map-get(map-get($fish, orange), "goldfish-2");
}
h3 {
color: map-get(map-get($fish, orange), "goldfish-3");
}


codepen 2

Is it even possible or is there a similar way to execute this?

Answer

I don't think it's possible to loop inside a map

However this is how you can achieve what you want easily. I am using the sass syntax

$oranges: #af5422 #FFCA28 #FFA000
$orange: ()

@each $current-colour in $oranges
  $i: index($oranges, $current-colour)
  $orange: map-merge($orange, ("goldfish-#{$i}": $current-colour))

$fish: (orange: $orange) !default

h1
  color: map-get(map-get($fish, orange), "goldfish-1")

h2 
  color: map-get(map-get($fish, orange), "goldfish-2")

h3 
  color: map-get(map-get($fish, orange), "goldfish-3")

This is the scss syntax

$oranges: #af5422 #FFCA28 #FFA000;
$orange: ();

@each $current-colour in $oranges {
  $i: index($oranges, $current-colour);
  $orange: map-merge($orange, ("goldfish-#{$i}": $current-colour));
}

$fish: (orange: $orange) !default;

h1 {
  color: map-get(map-get($fish, orange), "goldfish-1");
}

h2 {
  color: map-get(map-get($fish, orange), "goldfish-2");
}

h3 {
  color: map-get(map-get($fish, orange), "goldfish-3");
}

They both compile to the following css

h1 {
  color: #af5422; }

h2 {
  color: #FFCA28; }

h3 {
  color: #FFA000; }