Pass function or mixin by reference in SASS

Functions and mixins are not first-class in Sass, meaning you can’t pass them around as arguments like you can with variables.

Sass 3.2 and older

The closest you can get is with the @content directive (Sass 3.2+).

@mixin foo {
    a {
        @content;
    }
}

@include bob {
    b: foo(c); // this replaces `@content` in the foo mixin
}

The only caveat is that the @content can’t see what’s inside your mixin. In other words, if c was only defined inside the bob mixin, it essentially wouldn’t exist because it isn’t considered in scope.

Sass 3.3 and newer

Starting with 3.3, you can use the call() function, but it is only for use with functions, not mixins. This requires passing string containing the name of the function as the first argument.

@function foo($value) {
    @return $value;
}

@mixin bob($fn: null) {
    a {
        b: call($fn, c);
    }
}

@include bob('foo');

Leave a Comment