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 ?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With