正如标题所说,我正在尝试检查 SASS 中是否定义了变量。 (如果这有什么不同的话,我正在使用指南针)
我发现 Ruby 的等价物是:
defined? foo
在黑暗中尝试了一下,但它只是给了我错误:
defined": expected "{", was "?
我找到了一个解决方法(显然只是在所有情况下定义变量,在这种情况下它实际上更有意义)但我真的很想知道这在未来是否可能
对于 Sass 3.3 及更高版本
从 Sass 3.3 开始,有一个variable-exists()
功能。从变更日志 http://sass-lang.com/documentation/file.SASS_CHANGELOG.html:
- 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 */
}
对于 Sass 3.2.x 及更早版本(我原来的答案)
我今天遇到了同样的问题:尝试检查是否设置了变量,如果设置了,则添加样式、使用 mixin 等。
读完之后isset()
功能不会被添加到 sass 中 https://github.com/nex3/sass/issues/47,我找到了一个简单的解决方法,使用!default http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#variable_defaults_关键词:
@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;
}
}
If false
是变量的有效值,您可以使用:
@mixin my_mixin() {
$base-color: null !default;
@if $base-color != null {
color: $base-color;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)