$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 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;
}
}
2 回答
对于Sass 3.3及更高版本
截至Sass 3.3,有一个
variable-exists()
函数 . 来自the changelog:用法示例:
对于Sass 3.2.x及更早版本(我的原始答案)
我今天遇到了同样的问题:尝试检查是否设置了变量,如果是这样,添加样式,使用mixin等 .
在读完
isset()
函数isn't going to be added to sass之后,我找到了一个使用!default关键字的简单解决方法:如果
false
是变量的有效值,则可以使用:作为补充答案 - 对于某些用例,您应该查看
default
关键字 . 它使您可以为变量分配默认值,以防它们尚未定义 .例:
在specific-variables.scss中你有:
在default-variables.scss中你有:
您的项目是这样构建的:
@import“specific-variables.scss”; @import“default-variables.scss”; @import“style.scss”;
品牌 Value 将是My Awesome Brand,品牌颜色的 Value 将是#0074BE .