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

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

问题描述

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

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

例如

...

我们的 CSS 使用的是 LESS.

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

.example_module.green { 背景:@green;}.example_module.red { 背景:@red;}.example_module.blue { 背景:@blue;}等等

我希望能够将所有这些颜色名称设置为一个数组并对其进行迭代.如果我们以后添加颜色,我们只需要在一个地方添加它.

伪代码:

@colors: ['green', 'red', 'blue'];对于@colors { 中的每个@color.example_module.@color { 背景:@color;}}

LESS 中是否也支持这样的功能?

解决方案

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

@colors:绿、红、蓝;.example_module {.-(@i: length(@colors)) 当 (@i > 0) {@name:提取(@colors,@i);&.@{name} {背景:@@name}.-((@i - 1));} .-;}

- - -

在 Modern Less 中,在 列表 插件:

@colors:绿、红、蓝;.for-each(@colors 中的@name){.example_module.@{name} {背景:@@name;}}

- - -

在 Legacy Less 中,语法糖可以使用:

@import "for";@colors:绿色,红色,蓝色;.example_module {.for(@colors);.-each(@name) {&.@{name} {背景:@@name}}}

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

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.

eg.

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

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.

Pseudo code:

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

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

Is something like this even supported in LESS?

解决方案

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));
    } .-;
}

- - -

In Modern Less the same can be more straight-forward with the help of the Lists plugin:

@colors: green, red, blue;

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

- - -

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}
    }
}

Where the imported "for" snippet (it's just a wrapper mixin for recursive Less loops) can be found here (with examples here and here).

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

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