1

I have loop in less which is iterating throw numbered variables with colors. It's working fine when I need just evaluate color but not when I want also change color with function.

@cat-1:#c40009;
....

.gen-cats-filter (@index,@prefix) when (@index > 0) {
  .@{prefix}@{index}{
   background-color: ~"@{cat-@{index}}";
   &:hover{
     background-color: darken(~"@{cat-@{index}}", 20%);
   }
  }
  .gen-cats-filter(@index - 1,@prefix);
}
.gen-cats(14,cat);

but this throws error.

is there way how to make it work and on hover make color darker??

zajca
  • 2,288
  • 4
  • 30
  • 40
  • I'd suggest you to use native list array/list capabilities instead of emulating arrays with variable name concatenation. See http://stackoverflow.com/questions/21941983/less-variables-is-this-possible for example. – seven-phases-max Jun 30 '14 at 19:43
  • 2
    Here's [codepen](http://codepen.io/seven-phases-max/pen/AmeDq) with example of the more "clean" solution for this use-case. – seven-phases-max Jun 30 '14 at 20:09
  • 1
    @seven-phases-max: Nice mixin for the `for` loop. Small but very effective and useful. – Harry Jul 01 '14 at 02:13

1 Answers1

2

Recommended Solution:

Actually, I made the above a lot more complicated than required. A simple option would be to just form the variable name using concatenation and then evaluate it within the darken() function itself instead of using the ~"" (which outputs a String instead of a Color).

&:hover{
   @clr: "@{prefix}-@{index}";
   background-color: darken(@@clr,20%);
}

Original Answer:

Assuming I understood your query correctly, you can achieve it the below way:

@cat-1:#c40009;
@cat-2:#0009c4;

.gen-cats-filter (@index,@prefix) when (@index > 0) {
  .@{prefix}@{index}{
    background-color: ~"@{@{prefix}-@{index}}";
   &:hover{
      @clr: "@{@{prefix}-@{index}}";
      background-color: darken(color(~"`function(){return @{clr}}()`"),20%);
   }
  }
  .gen-cats-filter(@index - 1,@prefix);
}
.gen-cats-filter(2,cat); //I assumed this line was an error in your code and hence modified it.
  1. @clr: "@{@{prefix}-@{index}}"; - Just for reducing the complexity of the next line. This evaluates to "#00c409" for @cat-1.
  2. color(~"`function(){return @{clr}}()`") - Converts the string into a color value that can be used within the darken function.
  3. darken() - Darkens the color value.

CodePen Demo


With recent updates to the Less compiler, we can avoid the JS function bit also and directly write it as follows:

background-color: darken(color(@clr),20%);
Harry
  • 87,580
  • 25
  • 202
  • 214
  • 1
    +1 for your Edit. [Here](https://gist.github.com/seven-phases-max/6113d506fbd3c85acb89#file-nested-variable-interpolations-less) I sketched a cheat sheet of the dark side of the "nested variable interpolations" technique used in the original snippet. – seven-phases-max Jul 02 '14 at 12:15