I have a LESS loop that generates different CSS (incremental) classes extracting color values from a list.
My current LESS code is the following:
.generate-detached(#f00, #0f0, #00f);
.generate-detached(@colors...)
{
.generate-detached-loop(1, @colors);
}
.generate-detached-loop(@i; @colors) when (@i <= length(@colors)) {
@color: extract(@colors, @i);
.detached-@{i}
{
box-shadow: inset 0px 0px 8px 2px @color;
> .toolbar > .drag-controls_container > .drag-control:before
{
box-shadow: inset 0px 0px 5px 1px @color;
}
}
.generate-detached-loop((@i + 1), @colors);
}
The resulting CSS code is:
.detached-1 {
box-shadow: inset 0px 0px 8px 2px #f00;
}
.detached-1 > .toolbar > .drag-controls_container > .drag-control:before {
box-shadow: inset 0px 0px 5px 1px #f00;
}
.detached-2 {
box-shadow: inset 0px 0px 8px 2px #0f0;
}
.detached-2 > .toolbar > .drag-controls_container > .drag-control:before {
box-shadow: inset 0px 0px 5px 1px #0f0;
}
.detached-3 {
box-shadow: inset 0px 0px 8px 2px #00f;
}
.detached-3 > .toolbar > .drag-controls_container > .drag-control:before {
box-shadow: inset 0px 0px 5px 1px #00f;
}
Maybe I'm using old LESS constructs and actually exist some new techniques or in general... have you any idea to improve solution?
It's more about your knowledge and understanding of existing language features rather than about language features themselves.
I.e. even in Less v2 (you're probably using) it's difficult to justify the existence of 4 extra lines of the .generate-detached(@colors...)
mixin you have there.
E.g. why not:
@detached-colors: #f00 #0f0 #00f;
.detached-loop(@i: length(@detached-colors)) when (@i > 0) {
.detached-loop(@i - 1);
.detached-@{i} {
@c: extract(@detached-colors, @i);
box-shadow: inset 0px 0px 8px 2px @c;
> .toolbar > .drag-controls_container > .drag-control:before {
box-shadow: inset 0px 0px 5px 1px @c;
}
}
} .detached-loop;
Or:
.make-detached(#f00 #0f0 #00f);
.make-detached(@colors, @i: length(@colors)) when (@i > 0) {
.make-detached(@colors, @i - 1);
.detached-@{i} {
@c: extract(@colors, @i);
box-shadow: inset 0px 0px 8px 2px @c;
> .toolbar > .drag-controls_container > .drag-control:before {
box-shadow: inset 0px 0px 5px 1px @c;
}
}
}
?
Less v3 has each
function:
each(#f00 #0f0 #00f, {
.detached-@{index} {
box-shadow: inset 0px 0px 8px 2px @value;
> .toolbar > .drag-controls_container > .drag-control:before {
box-shadow: inset 0px 0px 5px 1px @value;
}
}
});
But the similar thing exists for Less v2 as a plugin:
.for-each(@c, @i in @l: #f00 #0f0 #00f) {
.detached-@{i} {
box-shadow: inset 0px 0px 8px 2px @c;
> .toolbar > .drag-controls_container > .drag-control:before {
box-shadow: inset 0px 0px 5px 1px @c;
}
}
}