在LESS中循环遍历一组名称/值对 [英] Loop over an array of name value pairs in LESS

查看:75
本文介绍了在LESS中循环遍历一组名称/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让LESS的名称/值对数组循环?像这样:

Is there some way to loop an array of name/value pairs LESS? Something like this:

arr = alice: black, bob: orange;

.for(arr) // something something //
   .cl-@{name} {
       background-color: @{value}
   }

要生成类似这样的内容:

To generate something like this:

.cl-alice { background-color: black; }
.cl-bob { background-color: orange; }

我知道您可以对一个数组进行循环,但是我不确定它是否可以是一个数组对象而不是LESS中的值.

I know that you can for-loop an array, but I'm unsure if it can be an array of objects rather than values in LESS.

推荐答案

@ seven-phases-max给出的答案效果很好.为了完整起见,您还应该注意,在没有导入的"for"代码段的情况下,您可以在Less中执行相同的操作.

The answer given by @seven-phases-max works very well. For completeness you should also notice that you can do the same in Less without the imported "for" snippet.

来自lesscss.org

from lesscss.org

试图尽可能接近于声明性 CSS,Less选择通过受保护的对象执行条件执行 用@media查询代替mixins而不是if/else语句 功能规格.

In trying to stay as close as possible to the declarative nature of CSS, Less has opted to implement conditional execution via guarded mixins instead of if/else statements, in the vein of @media query feature specifications.

在Less中,mixin可以自称.结合使用此类递归混合 与Guard表达式和模式匹配一​​起使用,可用于创建 各种迭代/循环结构.

In Less a mixin can call itself. Such recursive mixins, when combined with Guard Expressions and Pattern Matching, can be used to create various iterative/loop structures.

所以在Less中,您可以写:

So in Less you could write:

@array: alice black, bob orange;

.createcolorclasses(@iterator:1) when(@iterator <= length(@array)) {
    @name: extract(extract(@array, @iterator),1);
    .cl-@{name} {
        background-color: extract(extract(@array, @iterator),2);
    }
    .createcolorclasses(@iterator + 1);
}
.createcolorclasses();

或者实际上:

@array: alice black, bob orange;

.createcolorclasses(@iterator:1) when(@iterator <= length(@array)) {
    @name: extract(extract(@array, @iterator),1);
    &@{name} {
        background-color: extract(extract(@array, @iterator),2);
    }
    .createcolorclasses(@iterator + 1);
}
.cl-{
    .createcolorclasses();
}

这篇关于在LESS中循环遍历一组名称/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆