Reputation: 37836
I have a bunch of color variables declared:
@green: #00a75c;
@darkgreen: #118335;
@blue: #0099ff;
@orange: #f7931e;
@sapphire: #303a96;
@gray: #4d4d4d;
The CMS I'm using has each color as an option. Therefore, the generated html will have one of these color names as a sibling. Something like this gets generated:
<div class="thing orange">
</div>
This is currently how I target the element in my less code:
.thing{
&.orange{
color: @orange;
border: @orange solid 1px;
}
&.blue{
color: @blue;
border: @blue solid 1px;
}
&.sapphire{
color: @sapphire;
border: @sapphire solid 1px;
}
&.green{
color: @green;
border: @green solid 1px;
}
&:hover{
text-decoration: none;
color: white;
&.orange{background-color: @orange;}
&.blue{background-color: @blue;}
&.sapphire{background-color: @sapphire;}
&.green{background-color: @green;}
}
}
What is the best way to refactor this? Do I need to make little mixins, one giant mixin? Can I loop over the colors somehow?
Upvotes: 0
Views: 423
Reputation: 15609
Based on the comments from seven-phases-max, here is an example implementation.
@colours:
'green' #00a75c,
'darkgreen' #118335,
'blue' #0099ff,
'orange' #f7931e,
'sapphire' #303a96,
'gray' #4d4d4d;
.generate-colour-classes(@index: length(@colours)) when (@index >0) {
@colour: extract(@colours, @index);
@property-name: e(extract(@colour, 1));
@property-value: extract(@colour, 2);
.generate-colour-class(@property-name; @property-value);
.generate-colour-classes(@index - 1);
}
.generate-colour-class(@name; @value){
&.@{name} {
color: @value;
border: @value solid 1px;
}
}
.thing {
.generate-colour-classes();
}
Upvotes: 1