在Less中循环遍历变量名称数组

Jas*_*rga 50 loops less

在我们的应用程序中,我们有一个预设的颜色列表供用户选择,与该用户相关的所有内容都将具有该颜色.

在整个应用程序中,我们将有各种模块,其颜色附加为类名.

例如.

<div class="example_module green">
  ...
</div>
Run Code Online (Sandbox Code Playgroud)

我们在CSS中使用LESS.

在很多地方我们都在做这样的事情:

.example_module.green { background: @green; }
.example_module.red { background: @red; }
.example_module.blue { background: @blue; }
etc
Run Code Online (Sandbox Code Playgroud)

我希望能够将所有这些颜色名称设置为数组并迭代它们.如果我们将来添加颜色,我们只需将它添加到一个地方.

伪代码:

@colors: ['green', 'red', 'blue'];

for each @color in @colors {
  .example_module.@color { background: @color; }
} 
Run Code Online (Sandbox Code Playgroud)

在LESS中甚至支持这样的东西吗?

sev*_*max 84

请参阅循环.例如(假设@green,@red,@blue变量别处定义):

@colors: green, red, blue;

.example_module {
    .-(@i: length(@colors)) when (@i > 0) {
        @name: extract(@colors, @i);
        &.@{name} {background: @@name}
        .-((@i - 1));
    } .-;
}
Run Code Online (Sandbox Code Playgroud)

- - -

在Modern Less中,在Lists插件的帮助下可以更直接:

@colors: green, red, blue;

.for-each(@name in @colors) {
    .example_module.@{name} {
        background: @@name;
    }
}
Run Code Online (Sandbox Code Playgroud)

- - -

在Legacy Less中,可以使用以下方法实现语法糖:

@import "for";

@colors: green, red, blue;

.example_module {
    .for(@colors); .-each(@name) {
        &.@{name} {background: @@name}
    }
}
Run Code Online (Sandbox Code Playgroud)

这里"for"可以找到导入的片段(它只是递归Less循环的包装混合)(这里这里有示例).

  • SyntaxError:对第6行第3行的common.less中的无效类型的操作:````5.example_module {6 .for(@colors); .-each(@color){7 @name:e(@color); ```by lessc 1.7.5 (2认同)

Ed *_*sky 14

这个mixin对我来说很好.第二个参数是一个代码块,可以访问当前迭代元素(@value)和索引(@i).

  1. 定义mixin:

    .for(@list, @code) {
        & {
            .loop(@i:1) when (@i =< length(@list)) {
                @value: extract(@list, @i);
    
                @code();
    
                .loop(@i + 1);
            }
    
            .loop();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用:

    @colors: #1abc9c, #2ecc71, #3498db, #9b59b6;
    
    .for(@colors, {
        .color-@{i} {
            color: @value;
        }
    });
    
    Run Code Online (Sandbox Code Playgroud)
  3. 结果css:

    .color-1 {
      color: #1abc9c;
    }
    .color-2 {
      color: #2ecc71;
    }
    .color-3 {
      color: #3498db;
    }
    .color-4 {
      color: #9b59b6;
    }
    
    Run Code Online (Sandbox Code Playgroud)


eye*_*hUp 13

使用现代 LESS (>= 3.7),您可以使用内置each函数:

/* (assuming @clr-green, @clr-red, @clr-blue variables are defined elsewhere) */
@colors: {
  green: @clr-green;
  red: @clr-red;
  blue: @clr-blue;
}

each(@colors, {
  .example_module.@{key} {
    background: @value;
  }
});
Run Code Online (Sandbox Code Playgroud)