Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass check if variable is passed to mixin

Tags:

variables

sass

Lets say I have a mixin with default values

$default: 1;

@mixin test($p : $default) {
    @if () {
        // Do something if $p was 4passed?
    } @else {
        // Do something if $p was not passed?
    }

}

If I was to call the mixin like so, two different was:

@include test(); // A
@include test(1);  // B

Is there a way I can tell the difference between the default (A), and the one that's overwriting the default (B)?

like image 390
Shannon Hochkins Avatar asked Mar 27 '14 04:03

Shannon Hochkins


1 Answers

Your mixin would work if you modify it a tiny bit (as you actually need to pass the parameter in question to the @if directive. And you would want to default the parameter to null or false, which would mean that nothing was passed).

@mixin test($p: null) {
    @if ($p) {
        /* Do something if $p was passed */
    } @else {
        /* Do something if $p was not passed */
    }
}

DEMO

If you want to set a different value as the default, then you just need to check for that specific value in the if statement (e.g. "do something if $p is set to the default value"). Here how you would do this by setting the default from a variable, like you do in your example. However, this will not differentiate between "no argument passed" and "passed value equals default value".

@mixin test($p: $default) {
    @if ($p == $default) {
      /* Do something if $p is set to $default */
    } @else {
      /* Do something else if $p is not $default */
    }
}

DEMO

But of corse you can combine both approaches ... check if something is passed to $p (to do different things if passed or not), and if nothing is passed set $p's value to default.

@mixin test($p: null) {
    @if ($p) {
      /* Do something if argument passed */
    } @else {
      /* Do something else if no argument passed. Set $p to default. */
      $p: $default;
    }
}

DEMO

This should now work for everything but the boolean value of false, as null and false both validate to false with the @if directive. So to allow passing false as an argument value you would need to use a more specific expression. For example:

...
    @if ($p != null) {
...

DEMO

And voilà, this should do the trick - unless you, for some reason, want to pass null as an argument. Then you need to use something else as the default, like a string that is extremely unlikely to be passed as an argument, e.g. "no arguments have been passed" =)

DEMO

like image 193
Martin Turjak Avatar answered Oct 20 '22 14:10

Martin Turjak