Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

ruby - Checking if a variable is defined in SASS

AS the title says I am trying to check whether a variable is defined in SASS. (I am using compass if that makes any different difference)

I've found the Ruby equivalent which is:

defined? foo

Gave that a shot in the dark but it just gave me the error:

defined": expected "{", was "?

I've found a work around (which is obviously just to define the variable in all cases, which in this case it actually makes more sense) but I'd really like to know if this is possible for the future

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For Sass 3.3 and later

As of Sass 3.3 there is a variable-exists() function. From the changelog:

  • It is now possible to determine the existence of different Sass constructs using these new functions:
    • variable-exists($name) checks if a variable resolves in the current scope.
    • global-variable-exists($name) checks if a global variable of the given name exists. ...

Example usage:

$some_variable: 5;
@if variable-exists(some_variable) {
    /* I get output to the CSS file */
}
@if variable-exists(nonexistent_variable) {
    /* But I don't */
}

For Sass 3.2.x and earlier (my original answer)

I ran into the same problem today: trying to check if a variable is set, and if so adding a style, using a mixin, etc.

After reading that an isset() function isn't going to be added to sass, I found a simple workaround using the !default keyword:

@mixin my_mixin() {
  // Set the variable to false only if it's not already set.
  $base-color: false !default;

  // Check the guaranteed-existing variable. If it didn't exist 
  // before calling this mixin/function/whatever, this will 
  // return false.
  @if $base-color {
     color: $base-color;
  }
}

If false is a valid value for your variable, you can use:

@mixin my_mixin() {
  $base-color: null !default;

  @if $base-color != null {
     color: $base-color;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...