I am creating a themeing system for a WordPress network that supports multiple layout themes that can support color schemes for a variety of universities. To do so, I periodically compile a LESS file (using lessphp) with school-specific variables and essentially use it as a library of helper classes in the themes.
Each school has 3 colors defined in LESS as: @primary
, @secondary
and @tertiary
. The method is straightforward and functional but requites a lot of repetition in the code. For example:
//Modifier Classes
.primary-lighter-text {
color: lighten(@primary,20);
}
.sec-lighter-text {
color: lighten(@secondary,20);
}
.tert-lighter-text {
color: lighten(@tertiary,20);
}
//Backgrounds
.primary-bg {
background-color: @primary;
}
.sec-bg {
background-color: @secondary;
}
.tert-bg {
background-color: @tertiary;
}
//Borders
.primary-border{
border-color: @primary;
}
.sec-border {
border-color: @secondary;
}
.tert-border {
border-color: @tertiary;
}
Nothing complicated from a LESS standpoint, but if I want to add a new helper class, I have to create 3. Is there a more succinct way to achieve this?
You can simplify it by making use of array loops. All you have to modify in case of a new addition would be to modify the array variables at the end.
.loop-column(@index) when (@index > 0) { /* Recursive Mixin with Guard condition. Mixin is processed only when the condition is satisfied */
.loop-column(@index - 1); /* Call the mixin again with a decremented counter */
@ctype: extract(@type, @index); /* Extract the type value corresponding to the index from the array */
@color: extract(@colors, @index); /* Extract the color value corresponding to the index from the array */
/* Form and Output the necessary classes and properties */
.@{ctype}-lighter-text { /* Selector interpolation to dynamically form the selector */
color: lighten(@color,20);
}
.@{ctype}-bg {
background-color: @color;
}
.@{ctype}-border{
border-color: @color;
}
}
.loop-column(length(@type));
@type: primary, sec, tert; /* The color types array */
@colors:#fff, #777, #000; /* The color value array for each type */
/* If required the colors can be kept as separate variables also. Refer 2nd demo. */
Update: (Based on comments from Andrew Cafourek and seven-phases-max)
Since LessPHP is outdated, the following line should be added and the length(@type)
should be replaced with the actual count.
.loop-column(0) {};
.loop-column(4);