LESS: Loop using data stored in an array (or something similar)

帅比萌擦擦* 提交于 2019-12-20 02:36:10

问题


I found this example in LESS documentation:

LESS:

.generate-columns(4);

.generate-columns(@n, @i: 1) when (@i =< @n) {
  .column-@{i} {
    width: (@i * 100% / @n);
  }
  .generate-columns(@n, (@i + 1));
}

OUTPUT CSS:

.column-1 {
  width: 25%;
}
.column-2 {
  width: 50%;
}
.column-3 {
  width: 75%;
}
.column-4 {
  width: 100%;
}

This loop generates 4 different divs because '4' was the value passed by firs mixin's call, but generated values are entirely calculated inside mixin. In other words, @n implicitly indicates "number of iterations".

I would like to be able to set a sort of "array of values" such as:

PSEUDO-CODE:

.generate-columns( [25,50,75,100] );

that should be passed to loop mixin and then generates the same CSS code, using each array's value. Is it possible?


回答1:


.generate-columns-loop(@i; @widths) when (@i <= length(@widths)) {
  .column-@{i} {
    @width: extract(@widths, @i);
    width: (@width * 1%);
  }
  .generate-columns-loop((@i + 1), @widths);
}
.generate-columns(@widths...) {
  .generate-columns-loop(1, @widths);
}

.generate-columns(25, 50, 75, 100);



回答2:


You can pass an array list to the mixin and then use the extract function to extract the value corresponding to the iteration number and use it.

.generate-columns(@n: 4; @list: 10, 20, 30, 40 );

.generate-columns(@n; @i: 1; @list) when (@i =< @n) {
  .column-@{i} {
    width: percentage((extract(@list, @i)/100)); /* built-in function to convert numeric to percentage */
  }
  .generate-columns(@n; (@i + 1);  @list);
}

or like below (basically same functionality as the above one with the only difference being that in the above snippet we are using named parameters feature because we are skipping providing a value for the @i variable in the mixin call.)

@widths: 10, 20, 30, 40, 50;

.generate-columns(5; 1; @widths);

.generate-columns(@n; @i: 1; @list) when (@i =< @n) {
  .column-@{i} {
    width: percentage((extract(@list, @i)/100));
  }
  .generate-columns(@n; (@i + 1);  @list);
}


来源:https://stackoverflow.com/questions/28151864/less-loop-using-data-stored-in-an-array-or-something-similar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!