且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查变量是否在 SASS 中定义

更新时间:2023-11-25 22:39:40

适用于 Sass 3.3 及更高版本

从 Sass 3.3 开始,有一个 variable-exists() 函数.来自变更日志:

  • 现在可以使用这些新函数确定不同 Sass 结构的存在:
    • variable-exists($name) 检查变量是否在当前范围内解析.
    • global-variable-exists($name) 检查给定名称的全局变量是否存在....
    • 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. ...

    示例用法:

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

    对于 Sass 3.2.x 及更早版本(我的原始答案)

    我今天遇到了同样的问题:尝试检查是否设置了变量,如果设置了,则添加样式、使用 mixin 等.


    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.

    在阅读了 isset() 函数后 不会被添加到 sass,我找到了一个简单的解决方法,使用 !default 关键字:

    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;
      }
    }
    

    如果 false 是变量的有效值,您可以使用:

    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;
      }
    }