0

So I am writing a web app that has themes say light(default) and dark. I am using SCSS as per this article How to Create a Dark Mode in Sass. I can create light and dark and also can create multiple themes. But I have to achieve something like this.

Here is the scenario:

I have a question, in the mentioned workaround in the article, What if I do not have bg: $bg--light, for dark version and have only for default. like this

$themes: (
        default: (
                logo: url("../images/brand/logo_vertical.svg"),
                bg: $bg--light,
                text: $text--light,
        ),
        dark: (
                logo: url("../images/brand/logo_vertical--invert.svg"),
                text: $text--dark,
        ),
);

@mixin themed() {
  @each $theme, $map in $themes {
    .theme--#{$theme} & {
      $theme-map: () !global;
      @each $key, $submap in $map {
        $value: map-get(map-get($themes, $theme), '#{$key}');
        $theme-map: map-merge($theme-map, ($key: $value)) !global;
      }
      @content;
      $theme-map: null !global;
    }
  }
}

@function t($key) {
  @return map-get($theme-map, $key);
}

.base {
  @include themed() {
    color: t($text);
    background: t($bg);
  }
}

This gives an error for no bg: $bg--light, in dark. Is there anything that I could do if bg: $bg--light, doesn't exist for dark or any other theme it will use of the default one.

Is this possible? how?

Is there any way I can write if condition to use the default if a key do not exist.

itsmnthn
  • 1,898
  • 1
  • 18
  • 30

1 Answers1

1

Yes, you can get what you want with a if condition. First, store your default theme in a variable:

$default-theme: map-get($themes, default);

Then, in your function t, check if the key exists with the built-in function map-has-key and use the result to select the desired theme map with a ternary operator:

@function t($key) {
  $key-exists: map-has-key($theme-map, $key);
  @return map-get(if($key-exists, $theme-map, $default-theme), $key);
}
Arkellys
  • 5,562
  • 2
  • 16
  • 40