【问题标题】:Resolving dynamic variables in LESS在 LESS 中解析动态变量
【发布时间】:2014-01-30 09:27:57
【问题描述】:

我正在尝试根据多个预定义变量 sn-ps 在循环中生成多个类。

我有一个 variables.less 文档,我在这个 less 文件的顶部导入该文档,其中包含我的颜色变量。然后我想为这些生成匹配的类,但我无法编译变量。

我的代码:

.loop-class(~"primary", ~"success", ~"info", ~"warning", ~"danger";);
.loop-class(@list, @index: 1) when (isstring(extract(@list, @index))) {
    @status: extract(@list, @index);

    .button-@{status} {
        color: ~'@button-@{status}';
    }
    .loop-class(@list, (@index + 1));
}

编译为:

.button-primary {
  color: @button-primary;
}
.button-success {
  color: @button-success;
}
etc etc

如你所见,我得到了正确连接的变量名,但我无法解析它,所以我猜 LESS 在使用这个函数之前已经完成了它的变量编译?

我已经尝试将变量移动到此文档中,以及将变量包装在 mixin 中并将其添加到 .loop-class 中,但这些似乎都没有帮助。

我也尝试过类似的方法:

@status: extract(@list, @index);
@compileClass: ~'@button-@{status}';

.button-@{status} {
    color: @compileClass;
}

我将变量保存在另一个变量中,然后引用它,但它会产生相同的结果。

我查看了less css calling dynamic variables from a loop 并尝试按如下方式实现:

.loop-class(~"primary", ~"success", ~"info", ~"warning", ~"danger";);
.define(@var) {
    @fallback: ~'@button-@{var}';
}

.loop-class(@list, @index: 1) when (isstring(extract(@list, @index))) {
    @status: extract(@list, @index);

    .button-@{status} {
        .define(@status);
        color: @@fallback;
    }
    .loop-class(@list, (@index + 1));
}

但这给了我@@button-danger(索引中的最后一个)未定义的错误,因此它仍然无法解析变量。

你们知道我做错了什么吗?

感谢您的帮助!

【问题讨论】:

  • 欢迎来到 Stack Overflow,感谢您为您的第一篇文章发布了一个格式良好的问题。
  • 非常感谢 Scott,感谢您解决了我的第一个问题! ;)

标签: variables less dotless


【解决方案1】:

缺少括号

您缺少一组解析变量所需的括号:

//imported from another file
@button-primary: cyan;
@button-success: green;
@button-info: orange;
@button-warning: yellow;
@button-danger: red;

//in your mixin file
.loop-class(~"primary", ~"success", ~"info", ~"warning", ~"danger";);
.loop-class(@list, @index: 1) when (isstring(extract(@list, @index))) {
    @status: extract(@list, @index);

    .button-@{status} {
    color: ~'@{button-@{status}}'; /* two more brackets needed */
              |                |
            here             here
    }
    .loop-class(@list, (@index + 1));
}

CSS 输出

.button-primary {
  color: #00ffff;
}
.button-success {
  color: #008000;
}
.button-info {
  color: #ffa500;
}
.button-warning {
  color: #ffff00;
}
.button-danger {
  color: #ff0000;
}

更简洁更友好的代码

此外,为了减少杂乱和用户友好的代码,您可以通过在 mixin 中将 isstring 更改为 iskeyword 来删除混合调用所需的多个字符串插值:

.loop-class(primary, success, info, warning, danger;); /* cleaner code on call */
.loop-class(@list, @index: 1) when (iskeyword(extract(@list, @index))) {
    @status: extract(@list, @index);

    .button-@{status} {
    color: ~'@{button-@{status}}';
    }
    .loop-class(@list, (@index + 1));
}

【讨论】:

  • 太好了,解决方案完美运行!很好地呼吁使用 iskeyword 代替,绝对让它更容易阅读和理解。非常感谢,斯科特!
猜你喜欢
  • 2020-11-27
  • 2019-02-27
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 2020-04-18
  • 1970-01-01
相关资源
最近更新 更多