ahmedelgabri ahmedelgabri - 5 months ago 11
Ruby Question

Check for a Variable in Sass mixin & print it if it's defined

I'm creating a Sass mixin with 3 arguments one of them is optional & I want to print it out if it's passed otherwise I don't want to print anything.

Here is how my mixin looks like:

@mixin name($arg1, $arg2, $arg3: false){
@if $arg3 { #{$arg3} , }
& {
color: #{$arg1};
> #{$arg2}{
&:before{
something...
}
}
}
}


but this doesn't work & it throws an error


Warning: Syntax error: Invalid CSS after "...$arg3}": expected "{", was "}"


So how can I achieve the desired result?

Answer

This would be how you would write it:

@mixin name($arg1, $arg2, $arg3: false) {
    $sel: ();
    @if $arg3 {
        $sel: append($sel, unquote($arg3));
    }
    $sel: append($sel, unquote('&'), comma);
    #{$sel} {
        color: #{$arg1};
        > #{$arg2} {
            &:before{
                border: 1px solid;
            }
        }
    }
}

.foo {
    @include name(yellow, blue, '.bar');
}

Output:

.foo .bar, .foo {
  color: yellow;
}

.foo .bar > blue:before, .foo > blue:before {
  border: 1px solid;
}

However, it might be better written like this:

@mixin name($arg1, $arg2) {
    color: #{$arg1};
    > #{$arg2} {
        &:before{
            border: 1px solid;
        }
    }
}

%foo, .foo {
    @include name(yellow, blue);
}

.foo .bar {
    @extend %foo;
}