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
and
So in Less you could write:
or indeed:
In Less a "pair" (in its simplest form) can be represented as an array too, so it can be as simple as:
Note however that the ".for" thing is limited to the only loop per scope so it's better to rewrite above to something like this:
The imported
"for"
snippet (it's just a wrapper mixin for recursive Less loops) can be found here (with examples here and here).While it is useful from the other answers to know that Less supports recursive functions and mixins, there is now a much simpler answer to this simple question. This solution is tested to work with Less v3.9, but should work back to Less v3.7 when each was introduced.
The output is tidy:
Want more? Well, as they say, "You can haz more". Use
@index
to use the 1-based index in the formula above.Here is one "parametric mixins" which you can use with "key:value" pairs.
Array of "key:value" pairs is defined as follows: @array: "key:value", "key:value";
Definition:
Test
Result:
It works for me using grunt + less@1.7.4