正如标题所说,我试图判断SASS中是否定义了变量.(如果罗盘有什么不同,我会用它)
我找到了Ruby的类似功能:
defined? foo
在黑暗中给了我一个机会,但它只是给了我一个错误:
defined": expected "{", was "?
我已经找到了一个解决办法(显然,这只是在所有情况下定义变量,在本例中,它实际上更有意义),但我真的很想知道这在future 是否可行
正如标题所说,我试图判断SASS中是否定义了变量.(如果罗盘有什么不同,我会用它)
我找到了Ruby的类似功能:
defined? foo
在黑暗中给了我一个机会,但它只是给了我一个错误:
defined": expected "{", was "?
我已经找到了一个解决办法(显然,这只是在所有情况下定义变量,在本例中,它实际上更有意义),但我真的很想知道这在future 是否可行
从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)
判断变量是否在当前范围内解析.global-variable-exists($name)
判断给定名称的全局变量是否存在.
用法示例:
$some_variable: 5;
@if variable-exists(some_variable) {
/* I get output to the CSS file */
}
@if variable-exists(nonexistent_variable) {
/* But I don't */
}
今天我遇到了同样的问题:试图判断是否设置了变量,如果设置了,则添加样式、使用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;
}
}