Can you use a loop on null arguments in a sass mixin?

Viewed 33

so I've been trying to figure this out but maybe I'm just beating my head against the wall. I'm trying to make a sass mixin that uses null arguments so that the argument will not be included unless a value is specifically assigned to the output like so:

// main mixin

@mixin fontSettings(
    $font-size: null,
    $line-height: null,
    ) 
{
 // if null, get the default value
   @if not $font-size {
       $font-size: -get-font-defaults(font-size);
   }
 // if null get, default value
   @if not $line-height {
    $line-height: -get-font-defaults(line-height);
    }
  // calculate font stuff
    $font-size: $font-size * 1rem;
    $line-height: $line-height * 1rem;
 //output
    font-size: $font-size;
    line-height: $line-height;

}

// map merge mixin
@mixin -set-font-defaults() {
    $-font-defaults: map-merge($-font-defaults, keywords($defaults)) !global;
}

// function to get map values
@function -get-font-defaults($key){
    @return map-get($-font-defaults, $key);
}

//  default settings config map
$-font-defaults: (
    'font-size': 1.2,
    'line-height': 2,
);

and usage would be

p {
 //output sets fontsize to 12px and line height to 20px
 @include fontSettings;
}

my question is - is there any way to shorten this without having to do an @if validation for each argument? like using a @each loop to loop through the arguments? I keep getting invalid null operations unless I do a validation for each argument separately. if there's no way to shorten this with a loop, then I'll accept that since I'm a noob but if there is a way to shorten this I would appreciate some advise on how to do so. I plan on adding more arguments to the mixing, this is just a test with the two. thanks in advance for any help.

1 Answers

There is an easier way, you need to leverage the optional parameters of the mixin in your favor. By using optional parameters, not defining them allows the default values set in the declaration to kick in like the example below.

@mixin fontSettings($font-size: 1.2, $line-height: 2) {
    font-size: $font-size * 1rem;
    line-height: $line-height * 1rem;
}
Related