OK, let's say that I have a Less file like so:
// Turquoise
@turquoise: #1ABC9C;
@turquoise-2: #16A085;
// Greens
@green: #2ECC71;
@green-2: #27AE60;
// Blues
@blue: #3498DB;
@blue-2: #2980B9;
// Navy Blues
@navy: #34495E;
@navy-2: #2C3E50;
// Purples
@purple: #9B59B6;
@purple-2: #8E44AD;
// Yellows
@yellow: #F1C40F;
// Oranges
@orange: #F39C12;
@orange-2: #E67E22;
@orange-3: #D35400;
// Reds
@red: #E74C3C;
@red-2: #C0392B;
// Greys
@grey: #ECF0F1;
@grey-2: #BDC3C7;
@grey-3: #95A5A6;
@grey-4: #7F8C8D;
@colour-scheme:
@red, @red-2,
@orange, @orange-2, @orange-3,
@yellow,
@green, @green-2,
@turquoise, @turquoise-2,
@blue, @blue-2,
@purple, @purple-2,
@navy, @navy-2,
@grey, @grey-2, @grey-3, @grey-4
;
And I wanted to make a mixin
that went like so:
.createBG( @colour-array: @colour-scheme, @n: length( @colour-scheme ), @i: 0 ){
&.<[COLOUR-ARRAY[@i] VARIABLE NAME]>{
background-color: extract( @colour-array, @i );
}
.createBG( @colour-array, ( @i + 1 ) )
}
How would I achieve to replace <[COLOUR-ARRAY[@i] VARIABLE NAME]>
with valid Less code that would give me the variable name of the current index of the list/array.
What would be the surefire, and best practice, way of implementing this?
You can do this using the extract
function itself by just setting the color variable names as value for the @color-scheme
variable instead of giving it the variable itself. Within the mixin, @@
can be used to resolve the variable's name to its actual color value.
@colour-scheme:
red, red-2, orange, orange-2, orange-3, yellow, green, green-2, turquoise, turquoise-2,
blue, blue-2, purple, purple-2, navy, navy-2, grey, grey-2, grey-3, grey-4;
.createBG(@colour-array: @colour-scheme, @n: length(@colour-scheme), @i: 1 ) when (@i <= @n){
@color: extract(@colour-array, @i);
&.@{color}{
background-color: @@color;
}
.createBG( @colour-array, @n, @i + 1 )
}
.createBG();
Since you need the color names also (to be the class name), you'd definitely have to store the names in some variable and so there is not much reduction possible. But we could still use associative array. A sample for associative array is provided below.
@colour-scheme:
red #E74C3C, red-2 #C0392B,
orange #F39C12, orange-2 #E67E22, orange-3 #D35400,
yellow #F1C40F,
green #2ECC71, green-2 #27AE60,
turquoise #1ABC9C, turquoise-2 #16A085,
blue #3498DB, blue-2 #2980B9,
purple #9B59B6, purple-2 #8E44AD,
navy #34495E, navy-2 #2C3E50,
grey #ECF0F1, grey-2 #BDC3C7, grey-3 #95A5A6, grey-4 #7F8C8D;
.createBG(@colour-array: @colour-scheme, @n: length(@colour-scheme), @i: 1 ) when (@i <= @n){
@color-name-hex: extract(@colour-array, @i);
@color-name: extract(@color-name-hex, 1);
@color-hex: extract(@color-name-hex, 2);
&.@{color-name}{
background-color: @color-hex;
}
.createBG( @colour-array, @n, @i + 1 )
}
.createBG();
Note: Have a look at this bug in v2.6.1 and it could end up spoiling your loops. It will be fixed though.