在Less中循环遍历变量名称数组 [英] Loop through array of variable names in Less

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

问题描述

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

In our app, we have a preset list of colors that a user can be choose from and everything related to that user will have that color.

在整个应用程序中,我们将提供带有颜色作为类名称附加的各种模块.

Throughout the app, we will have various modules with the color attached as a class name.

例如

<div class="example_module green">
  ...
</div>

我们在CSS中使用LESS.

We are using LESS for our CSS.

在许多地方,我们正在做这样的事情:

In a number of places we are doing things like this:

.example_module.green { background: @green; }
.example_module.red { background: @red; }
.example_module.blue { background: @blue; }
etc

我希望能够将所有这些颜色名称设置为数组并对其进行迭代.如果将来添加颜色,则只需将其添加到一个位置即可.

I'd like to be able to set all these color names as an array and iterate over them. If we add colors in the future, we only have to add it in one place.

伪代码:

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

for each @color in @colors {
  .example_module.@color { background: @color; }
} 

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

Is something like this even supported in LESS?

推荐答案

请参见循环. 例如(假设@green@red@blue变量在其他位置定义):

See Loops. For example (assuming @green, @red, @blue variables are defined elsewhere):

@colors: green, red, blue;

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

---

借助列表插件:

@colors: green, red, blue;

.for-each(@name in @colors) {
    .example_module.@{name} {
        background: @@name;
    }
}

---

在Legacy Less中,可以使用以下方法获得语法糖:

- - -

And in Legacy Less the syntactic sugar can be achieved using:

@import "for";

@colors: green, red, blue;

.example_module {
    .for(@colors); .-each(@name) {
        &.@{name} {background: @@name}
    }
}

可以在 查看全文

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