Search code examples
lessmixins

Can an optional LESS mixin variable refer to another variable


Is it possible to refer to another variable in a parametric mixin?

.button(@textColor : @white, @iconColor : @textColor) {
    color: @textColor;
    i {
        color: @iconColor
    }
}

I want @iconColor to default to the value of @textColor.

The LESS compiler is complaining.


Solution

  • I think you need to do a nested mixin idea to get your functionality you want. LESS cannot tell that you have already set the @textColor and use that as the default setting for the second parameter. Instead, you need to do some type of guard expression. Here, I have made that guard expression a nested mixin that evaluates the second parameter within the main mixin and responds accordingly to get the @iconColor set:

    .button(@textColor: @white, @setIconColor: null) {
    
        .setDefault() when (@setIconColor = null) {
           .doSetting(@textColor);
        }
        .setDefault() when (iscolor(@setIconColor)) {
           .doSetting(@setIconColor);
        }
        .setDefault();
    
        .doSetting(@iconColor) {    
            color: @textColor;
            i {
              color: @iconColor
            }
        }
    }