Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value in a Sass Map exists

Tags:

css

sass

In the following SASS-code snippet I want to check if a map has a specific key. If not, it returns a default value (in this case #bbb)

@function contains($list, $var) {
    @return (false == index($list, $var));
}

$colors: (aaa: #aaa, bbb: #bbb);

$out: if(contains($colors, aaa), map-get($colors, aaa), #bbb);

body {
   color: $out;
}

For some reason it always returns #bbb. Any suggestions what I'm doing wrong here ?

like image 700
Jeanluca Scaljeri Avatar asked Apr 03 '17 15:04

Jeanluca Scaljeri


1 Answers

The first issue is that the return value is null if the value isn't found:

@function contains($list, $var) {
    @return (null == index($list, $var));
}

The second issue relates to the semantics of your contains function. Usually a function called contains should return true if the value was found in the list and false otherwise (at least I would expect that):

@function contains($list, $var) {
    @return (null != index($list, $var));
}

Then there is a third issue with calling the index function on a map. You would have to pass a key-value pair not just the key to this function:

$out: if(contains($colors, aaa #aaa), map-get($colors, aaa), #bbb);

Now it works as expected but for the sake of completeness let me tell you that there is already a built-in function which does exactly what you try to achieve with your contains-function; the map_has_key($map, $key):

$out: if(map-has-key($colors, aaa), map-get($colors, aaa), #bbb);
like image 149
Marvin Avatar answered Oct 14 '22 12:10

Marvin