Search code examples
lessmixinsguard

LESS - set 3 variables depending on another variable's value


I've got a mixin that accepts two parameters:

.build-logo(ab, 200px);

The first is an acronym string for one of our products, and the second is square width/height of the desired logo. What I need is a set of guarded mixins that test against the value of the first parameter - but here's where my knowledge of LESS falls short.

I think it needs to be something like this, but I can't get the syntax down:

.set-logo-colors() when (@acronym = 'ab') {
    @first-color: red;
    @second-color: green;
    @third-color: blue;
}

Then the 3 color variables declared above need to be available in the previously mentioned .build-logo() mixin.

Any help, tips, or advice is welcome. Thank you!


Solution

  • You could write parameter specific mixins instead of using guards, like:

    .set-logo-colors(ab) {
        @first-color: red;
        @second-color: green;
        @third-color: blue;
    }
    .set-logo-colors(bc) {
        @first-color: orange;
        @second-color: blue;
        @third-color: gray;
    }
    

    which will be executed when you pass the right parameter.

    And to elaborate this approach a little, you could do something like:

    .logo(@product) {
        .set-logo-colors(@product);
        .build-logo(@product, 200px);
    }
    

    and lets say build-logo looks like this

    .build-logo(@a, @b) {
        product: @a;
        width: @b;
        color: @first-color;
    }
    

    by calling

    .logo(ac);
    

    you get:

    product: ab;
    width: 200px;
    color: #ff0000;
    

    More than one product:

    There will be a problem, if you call more than one product, the color variable will be already set and

    .logo(bc);
    

    will return:

    product: bc;
    width: 200px;
    color: #ff0000;
    

    which is not what we want.

    So it would be better to start with a set of multiparametric mixins:

    .build-logo(@a, @b, @color1, @color2, @colo3) {
        product: @a;
        width: @b;
        color: @color1;
    }
    
    .logo(ab, @size) {
        .build-logo (ab, @size, red, green, blue);
    }
    
    .logo(bc, @size) {
        .build-logo (bc, @size, green, orange, gray);
    }
    

    now calling

    .logo(ab, 200px);
    

    gives the same output as above, but it will not overlap/overwrite anything when calling it for another product. So:

    .logo(bc,200px);
    

    returns:

    product: bc;
    width: 200px;
    color: #008000;