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,370
  • 4
  • 20
  • 39

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,054
  • 1
  • 16
  • 24
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
  • 3,751
  • 6
  • 36
  • 56