正如标题所说,我正在尝试检查变量是否在 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/