正如标题所示我试图检查是否在SASS中定义了一个变量.(如果有任何不同的差异,我正在使用指南针)
我找到了Ruby等价物,它是:
defined? fooRun Code Online (Sandbox Code Playgroud)
在黑暗中给了一枪,但它只是给了我错误:
defined": expected "{", was "?
我找到了一个解决方法(显然只是在所有情况下定义变量,在这种情况下它实际上更有意义)但我真的想知道这是否可能在未来
Rob*_*obW 105
从Sass 3.3开始,有一个variable-exists()功能.来自更改日志:
- 现在可以使用这些新函数确定不同Sass结构的存在:
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 */
}
Run Code Online (Sandbox Code Playgroud)
我今天遇到了同样的问题:尝试检查是否设置了变量,如果是这样,添加样式,使用mixin等.
在看到isset()函数不会被添加到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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果false是变量的有效值,您可以使用:
@mixin my_mixin() {
$base-color: null !default;
@if $base-color != null {
color: $base-color;
}
}
Run Code Online (Sandbox Code Playgroud)
如果你正在寻找相反的东西,那就是
@if not variable-exists(varname)
Run Code Online (Sandbox Code Playgroud)
检查它是否未定义或错误:
@if not variable-exists(varname) or not $varname
Run Code Online (Sandbox Code Playgroud)
如果您只想在未定义或为空时设置它
$varname: VALUE !default;
Run Code Online (Sandbox Code Playgroud)