Loop over an array of name value pairs 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();
}

Leave a Comment