问题
I am trying to create a list which is calculated from another list. For example, if I have a list like 1,2,3,4... then the output has to be 10,20,30,40... Is there any other way to create a list from another in less? Please refer the below codes.
@input: 1,2,3,4;
.for(@array) when (default()) {.for-impl_(length(@array))}
.for-impl_(@i) when (@i > 1) {.for-impl_((@i - 1))}
.for-impl_(@i) when (@i > 0) {.-each(extract(@array, @i), @i)}
.create-list(@input){
.for(@input); .-each(@value, @a) {
.output_@{a}(@a) { // Create dynamic mixin based on input list
@output_@{a}: @a * 10; // Create dynamic variable to store each calc
}
}
}
.create-list(@input);
.loop(@count) when (@count > 0){
@prev: @count - 1;
.loop(@prev);
.first() when (@count = 1){
.output_@{count}(); // call first mixin which created already
@res_@{count}: @output_@{count} // Store the result in another dynamic var
}
.first() when not (@count = 1){
.output_@{count}();
@res_@{count}: @res_@{prev}, @output_@{count}; // join prev and current result
}
.first();
}
.loop(4);
The above implementation similar I expect like below.
.a1(){
@o1: #fff;
}
.a2(){
@o2: #aaa;
}
.a3(){
@o3: #ccc;
}
.loop(@counter) when (@counter > 0) {
.loop((@counter - 1));
.a1();
@out1: @o1;
.a2();
@out2: @out1, @o2;
.a3();
@out: @out2, @o3;
div{
colors: @out;
}
}
.loop(1);
and the output is #fff, #aaa, #ccc.
回答1:
You'll create a modified "list" by passing the concatenated result of each loop iteration to next iteration, thus the final iteration defines the actual result. E.g. (just illustrating the principle w/o adopting it to your use-case):
// usage:
@input: 1, 2, 3, 4;
result {
.modify-list(@input);
result: @result;
}
// impl:
.modify-list(@list) {
@n: length(@list);
.-(@n, extract(@list, @n) * 10);
.-(@i, @r) when (@i > 1) {
.-(@i - 1; extract(@list, @i - 1) * 10, @r);
}
.-(1, @r) {@result: @r}
}
Demo
Technically this code does not create a one dimensional list (i.e. the result there is not really equal to @result: 10, 20, 30, 40;
) but since in final CSS it's rendered identically it would work just fine.
Also assuming your original use-case was How to apply less functions to gradient colors?, you don't really need a code like this (i.e. it's an "XY Problem" and instead of generating a new variable with the new list, direct generation of the corresponding gradient values would be much less verbose and much more readable. See the linked answer in comments of the mentioned question).
来源:https://stackoverflow.com/questions/32665124/how-to-create-list-output-in-less