How can I test if a Sass function exists?
I have a Sass package that uses a custom Sass function. However, outside Ruby (e.g. libsass), that function may not be defined and a fallback is provided:
url: if($bootstrap-sass-asset-helper, twbs-font-path('name.eot'), 'name.eot')
I would like to set the value of $bootstrap-sass-asset-helper
to true or false depending on whether twbs-font-path
is declared.
The current version of Sass has a function-exists
function. Full example:
.foo {
@if function-exists(myfunc) {
exists: true;
}
@else {
exists: false;
}
}
This is new functionality to v3.3 (March 2014), so you may need to update your Sass gem to utilize it.
Sass v3.3 adds other existence tests too:
variable-exists($name)
global-variable-exists($name)
mixin-exists($name)
More on Sass v3.3.
Sass does not have such a feature. You could fudge it like this if you needed to:
@debug if(foo() == unquote("foo()"), false, true); // false
@function foo() {
@return true;
}
@debug if(foo() == unquote("foo()"), false, true); // true
This works because when you call a function that doesn't exist, Sass assumes that you might be writing valid CSS (calc, linear-gradient, attr, etc.). When this happens, what you've got is a string. So if the function exists, you get the results of the function instead of a string. So foo() == unquote("foo()")
is just checking to see if you got a string or not.
Related: Can you test if a mixin exists?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With