ruby - 检查变量是否在 SASS 中定义

标签 ruby sass

正如标题所说,我正在尝试检查变量是否在 SASS 中定义。 (如果有任何不同,我正在使用指南针)

我找到了 Ruby 的等价物,它是:

defined? foo

在黑暗中试了一下,但它给了我错误:

defined": 应该是 "{",是 "?

我找到了解决方法(这显然只是为了在所有情况下定义变量,在这种情况下它实际上更有意义)但我真的很想知道这在未来是否可行

最佳答案

对于 Sass 3.3 及更高版本

从 Sass 3.3 开始,有一个 variable-exists() 函数。来自 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. ...

示例用法:

$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 等。

在阅读完 isset() 函数后 isn't going to be added to sass ,我找到了一个使用 !default 的简单解决方法关键词:

@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 是您变量的有效值,您可以使用:

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

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

关于ruby - 检查变量是否在 SASS 中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8512802/

相关文章:

javascript - 在目录中显示完整图片

css - SASS 的 grunt-task 允许选项来强制执行代码样式

ruby - 调用系统命令会比 ruby​​ 方法更快吗?

ruby-on-rails - 在 rails 中向 link_to 添加方法和 html 选项?

ruby - 调试 Sinatra 应用程序

html - CSS Border Transition添加了多余的多余像素

sass - Gulp Sass 不编译部分

ruby-on-rails - Mechanize 设置具有重复名称的字段

ruby-on-rails - 在 seeds.rb 中关闭验证

css - 何时在 Sass 中使用@extend 和@mixin