Is there some way to loop an array of name/value pairs LESS? Something like this:
arr = alice: black, bob: orange;
.for(arr) // something something //
.cl-@{name} {
background-color: @{value}
}
To generate something like this:
.cl-alice { background-color: black; }
.cl-bob { background-color: orange; }
I know that you can for-loop an array, but I'm unsure if it can be an array of objects rather than values in LESS.
The answer given by @seven-phases-max works very well. For completeness you should also notice that you can do the same in Less without the imported "for"
snippet.
from lesscss.org
In trying to stay as close as possible to the declarative nature of CSS, Less has opted to implement conditional execution via guarded mixins instead of if/else statements, in the vein of @media query feature specifications.
and
In Less a mixin can call itself. Such recursive mixins, when combined with Guard Expressions and Pattern Matching, can be used to create various iterative/loop structures.
So in Less you could write:
@array: alice black, bob orange;
.createcolorclasses(@iterator:1) when(@iterator <= length(@array)) {
@name: extract(extract(@array, @iterator),1);
.cl-@{name} {
background-color: extract(extract(@array, @iterator),2);
}
.createcolorclasses(@iterator + 1);
}
.createcolorclasses();
or indeed:
@array: alice black, bob orange;
.createcolorclasses(@iterator:1) when(@iterator <= length(@array)) {
@name: extract(extract(@array, @iterator),1);
&@{name} {
background-color: extract(extract(@array, @iterator),2);
}
.createcolorclasses(@iterator + 1);
}
.cl-{
.createcolorclasses();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With