2

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
  • I wonder, your code even compiles, you may paste it in the right order.
    – Simplicius
    Commented Sep 3, 2020 at 21:18

1 Answer 1

1

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;
}
2
  • so if I did ` p { @include fontSettings; } h2 { @include fontSettings( $font-size: 1.8; ); } ` it wouldn't override the value in p and set them both to 1.8?
    – sassnoob
    Commented Sep 3, 2020 at 22:03
  • Correct, your <p> elements will have a font-size of 1.2rem and your <h2> items would be 1.8rem. Also in your example for the h2 rule you would only need to define the value like @include fontSettings(1.8)
    – macintosh
    Commented Sep 3, 2020 at 22:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.