Each函數(shù)是Less v3.7版本的新增用法,用于批量生成模板樣式。
文檔如下:
each Released v3.7.0
Bind the evaluation of a ruleset to each member of a list.c
把規(guī)則的計(jì)算綁定到列表的每一個成員身上
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:
每個列表成員可以被默認(rèn)綁定@value,@key,@index三個變量,對大部分的列表而言, @key和 @index會被定義為相同的值(比如以1開始的有序列表)。然而,你也可以使用規(guī)則自定義列表中的@key值
@set: {
one: blue;
two: green;
three: red;
}
.set {
each(@set, {
@{key}-@{index}: @value;
});
}
This will output:
輸出結(jié)果:
.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規(guī)則設(shè)定它的參數(shù),這樣會讓each()函數(shù)成為一個非常有用的函數(shù)
Setting variable names in each()
在each()中設(shè)置變量名
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()函數(shù)中你不必都使用@value,@key,@index作為變量名。在Less 3.7版本中,因?yàn)?code>each()函數(shù), Less被描述為可以接受匿名不定參數(shù),這一特性將會擴(kuò)展到其他的語法中
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:
一個匿名不定參數(shù)可以用#()或者 .()的樣式為開頭
.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()函數(shù)會獲取不定參數(shù)中的變量的名字并按順序把它們賦給到@value、@key、@index的value值。如果你只是寫了each(@list, #(@value){}), name@key和@value都不會被定義