In our app, we have a preset list of colors that a user can be choose from and everything related to that user will have that color.
Throughout the app, we will have various modules with the color attached as a class name.
eg.
<div class="example_module green">
...
</div>
We are using LESS for our CSS.
In a number of places we are doing things like this:
.example_module.green { background: @green; }
.example_module.red { background: @red; }
.example_module.blue { background: @blue; }
etc
I'd like to be able to set all these color names as an array and iterate over them. If we add colors in the future, we only have to add it in one place.
Pseudo code:
@colors: ['green', 'red', 'blue'];
for each @color in @colors {
.example_module.@color { background: @color; }
}
Is something like this even supported 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).