0

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?

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • 1
    See http://stackoverflow.com/questions/21440789. Though technically it's more elegant to have an array of colors instead of individual variables and an array of their names (see http://stackoverflow.com/questions/23658087 for example). – seven-phases-max Jul 17 '14 at 15:15
  • @seven-phases-max: Yes, the second option sounds much better. [This](http://stackoverflow.com/questions/24757612/simplifying-repetitive-less/24758422#24758422) is another related answer that I had posted yesterday. – Harry Jul 17 '14 at 15:27

1 Answers1

1

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();    
}
Community
  • 1
  • 1
Colin Bacon
  • 15,436
  • 7
  • 52
  • 72