2

How do I check if a SASS Map already exists and only define one if this is not the case?

I have tried:

@if ($myMap) {
// do someting
}

and

@if variable-exists($myMap) {
// do something
}

But I get the error "Undefined variable: "$myMap"? I'm sure this is pretty straghtforward but I can't seem to find the answer online?

Thanks

James Howell
  • 1,392
  • 5
  • 24
  • 42

2 Answers2

2

It's a little confusing, but when checking for a variable's existence, skip the $. You also need to set it as a global variable so it doesn't get scoped only to the @if block. This works:

@if variable-exists(myMap) == false {
  $myMap: (
    1: "foo",
    2: "bar"
  ) !global;
}

// ... now you can use your variable
mfluehr
  • 2,832
  • 2
  • 23
  • 31
0

You can set the map to exist as null be default, which means that if it isn't explicitly set anywhere, then the variable still exists but with a null value. You can then check if the value of the variable is null using an if statement.

$myMap: null !default;

@if $myMap == null {
  
}
Sam Willis
  • 4,001
  • 7
  • 40
  • 59