Search code examples
for-looplessmixins

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


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?


Solution

  • .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);