Sean Keenan
Sean Keenan

Reputation: 93

Use a particular Sass map depending on variable

I've run into an issue where it's easier for me to define two base maps that can be flicked between using a single variable (Seems easier for base, light/dark themes)

https://codepen.io/anon/pen/bLwNaW

I'm trying to set $theme-being-used, check it in a If/Else and use a particular map based on that result. This makes it simple for me to come in and set $theme-being-used to dark and change all of the base variables.

I've tried:

@if (#{$theme-being-used} == light) {

@if ($theme-being-used == light) {

@if (#{$theme-being-used} == "light") {, etc..

Does anyone know if this can be done? It's not a big deal either way, just saves a little bit of time when throwing up templated sites.

Before I was achieving this by simply comment/uncommenting code, i.e.

$palette: (
    // Light 
    ui: (
        primary:    #FFFFFF,
        secondary:  #EEEEEE,
        alternate:  #DDDDDD
    ),
    // Dark - COMMENTED when I want to use light variables
    /*ui: (
        primary:    #333,
        secondary:  #444,
        alternate:  #555
    ),*/
);

This is fine and pretty quick, but it'd just be easier to set it in one place and not have to do this.

Thanks.

Upvotes: 1

Views: 620

Answers (1)

3rdthemagical
3rdthemagical

Reputation: 5350

Place $theme-being-used check to _palette function. This function take only one parameter — color name. And contains all color select logic inside itself.

Sassmeister demo.

$theme-being-used: light;

$palette: (
    dark: (
        primary:   red,
        secondary: orange,
        tertiary:  blue
    ),
    light: (
        primary:   green,
        secondary: black,
        tertiary:  yellow
    )
);

@function _palette($color-name, $theme-name: $theme-being-used) {
  // Select one of available themes
  // Here there may be more complex logic in choosing themes
  $theme: map-get($palette, #{$theme-name});

  // Get the color from theme
  @return map-get($theme, #{$color-name});
}

.s-o {
  background: _palette(primary);

  &:hover {
    background: _palette(secondary);
  }
}

Upvotes: 2

Related Questions