Loop through array of variable names in Less

See Loops.
For example (assuming @green, @red, @blue variables are defined elsewhere):

@colors: green, red, blue;

.example_module {
    .-(@i: length(@colors)) when (@i > 0) {
        @name: extract(@colors, @i);
        &.@{name} {background: @@name}
        .-((@i - 1));
    } .-;
}

– – –

In Modern Less the same can be more straight-forward with the help of the Lists plugin:

@colors: green, red, blue;

.for-each(@name in @colors) {
    .example_module.@{name} {
        background: @@name;
    }
}

– – –

And in Legacy Less the syntactic sugar can be achieved using:

@import "for";

@colors: green, red, blue;

.example_module {
    .for(@colors); .-each(@name) {
        &.@{name} {background: @@name}
    }
}

Where the imported "for" snippet (it’s just a wrapper mixin for recursive Less loops) can be found here (with examples here and here).

Leave a Comment