nonnnnn
nonnnnn

Reputation: 693

Problem with Loop through nested sass maps

I have a simple sass map with colors. I loop through it and generate css vars. Works great so far.

$colors: (
  primary: red,
  secondary: blue,
)

@each $color, $value in $colors {
    --#{$color}: #{$value};
}

Then I extended this map with themes. There I loop through again per theme and create the css vars. This also works great.

$colors2: (
  theme-1: (
    primary: red,
    secondary: blue,
  ),
  theme-2: (
    primary: yellow,
    secondary: pink,
  )
)

@each $theme, $colors in $colors2 {
    &[data-theme="#{$theme}"] {
        @each $color, $value in $colors {
            --#{$color}: #{$value};
        }
    }
}

But now I need to find a way to combine the two. Unfortunately I haven't found a way so far to loop through the following list, create the individual css vars and the data-attributes + css vars.

$colors3: (
  primary: green,
  secondary: purple,
  theme-1: (
    primary: red,
    secondary: blue,
  ),
  theme-2: (
    primary: yellow,
    secondary: pink,
  )
)

Does anyone of you maybe have an idea how I can do this? In the end something like this should come out:

:root {
  --color-primary: green;
  --color-secondary: purple;

  &[data-theme="theme-1"] {
  --color-primary: red;
  --color-secondary: blue;
  }
  &[data-theme="theme-2"] {
  --color-primary: yellow;
  --color-secondary: pink;
  }
 }

Thank you very much for your help!

Kind regards Marco

Upvotes: 0

Views: 335

Answers (1)

nonnnnn
nonnnnn

Reputation: 693

i found a way to get it to work :)

here is my solution just in case, someone else needs it.

:root {
    @each $key, $value in $colors {
        @if type-of($value) == map {
            &[data-theme="#{$key}"] {
                @each $theme-key, $theme-value in $value {
                    --color-#{$theme-key}: #{$theme-value};
                }
            }
        } @else {
            --color-#{$key}: #{$value};
        }
    }
}

Upvotes: 2

Related Questions