Less 的Each用法

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都不会被定义

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,196评论 0 10
  • 或许一切都变了,也许一切从一开始就是假的.
    寸念阅读 1,036评论 0 0
  • 一直在寻找一个平台,可以记录一下自己每天的感想和总结。 在找另维的文章时,看到了简书,觉得简书的设计很简洁,完全符...
    茶小语阅读 1,337评论 0 0
  • 藏姐是我上一份工作的主管领导,称呼藏姐为藏姐既是礼貌也是约定俗成,我们一群小家伙都叫藏姐是藏姐,藏姐有多大?藏姐和...
    压力很大的六爷阅读 3,666评论 0 0
  • 老挝深处东南亚内陆,境内80%为山地和高原,且多被森林覆盖,有“印度支那屋脊”之称。美丽的自然风光与贫困朴实的生活...
    大凌河阅读 8,492评论 0 0

友情链接更多精彩内容