Sass check if variable is passed to mixin

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

Leave a Comment