Each函数是Less v3.7版本的新增用法,用于批量生成模板样式。
文档如下:
each Released v3.7.0
Bind the evaluation of a ruleset to each member of a list.c
把规则的计算绑定到列表的每一个成员身上
Example:
例如:
@selectors: blue, green, red;
each(@selectors, {
.sel-@{value} {
a: b;
}
});
Outputs:
输出:
.sel-blue {
a: b;
}
.sel-green {
a: b;
}
.sel-red {
a: b;
}
By default, each ruleset is bound, per list member, to a @value
, @key
, and @index
variable. For most lists, @key
and @index
will be assigned the same value (numerical position, 1-based). However, you can also use rulesets themselves as structured lists. As in:
每个列表成员可以被默认绑定@value
,@key
,@index
三个变量,对大部分的列表而言, @key
和 @index
会被定义为相同的值(比如以1开始的有序列表)。然而,你也可以使用规则自定义列表中的@key
值
@set: {
one: blue;
two: green;
three: red;
}
.set {
each(@set, {
@{key}-@{index}: @value;
});
}
This will output:
输出结果:
.set {
one-1: blue;
two-2: green;
three-3: red;
}
Since you can, of course, call mixins with guards for each ruleset call, this makes each()
a very powerful function.
因此你可以混合为每个each
规则设定它的参数,这样会让each()
函数成为一个非常有用的函数
Setting variable names in each()
在each()
中设置变量名
You don't have to use @value
, @key
, and @index
in your each()
function. In Less 3.7, with the each()
function, Less is introducing the concept of anonymous mixins, which may expand to other parts of the syntax at a later date.
在 每个each()
函数中你不必都使用@value
,@key
,@index
作为变量名。在Less 3.7版本中,因为each()
函数, Less被描述为可以接受匿名不定参数,这一特性将会扩展到其他的语法中
An anonymous mixin uses the form of #()
or .()
starting with .
or #
just like a regular mixin would. In each()
, you can use it like this:
一个匿名不定参数可以用#()
或者 .()
的样式为开头
.set-2() {
one: blue;
two: green;
three: red;
}
.set-2 {
// Call mixin and iterate each rule
each(.set-2(), .(@v, @k, @i) {
@{k}-@{i}: @v;
});
}
This outputs, as expected:
输出:
.set-2 {
one-1: blue;
two-2: green;
three-3: red;
}
The each()
function will take the variable names defined in the anonymous mixin and bind them to the @value
, @key
and @index
values, in that order. If you only write each(@list, #(@value) {})
, then neither @key
nor @index
will be defined.
each()
函数会获取不定参数中的变量的名字并按顺序把它们赋给到@value
、@key
、@index
的value值。如果你只是写了each(@list, #(@value){})
, name@key
和@value
都不会被定义
网友评论