Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test whether a Sass function is defined

Tags:

sass

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.

like image 526
glebm Avatar asked Dec 05 '22 08:12

glebm


2 Answers

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.

like image 103
KatieK Avatar answered Dec 15 '22 17:12

KatieK


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?

like image 23
cimmanon Avatar answered Dec 15 '22 19:12

cimmanon