简体   繁体   中英

How to get an inner variable inside a mixin in less?

I have tried to get variables inside a mixin and it won't work when using guards. I definitely missed something in the rule. Please refer to the below code snippet.

@list: #000, #fff;
div {
  .custom-colors(@list, 0%, 20%, true);   
   color: @gradient; // here I need the output
}

.custom-colors(@value, @light, @dark, @lightdark){   
    & when (@lightdark = true){
        @gradient: lighten(extract(@value, 1), @light), darken(extract(@value, 2), @dark);
    }    
    & when (@lightdark = false){
        @gradient:  darken(extract(@value, 1), @dark), lighten(extract(@value, 2), @light);
    }   
}

I got this error while executing the above code:

在此处输入图片说明

If I removed the guard condition, I can able to get the variable inside less mixin as below.

div {
  color: #000000, #cccccc;
}

What am I missing?

Your mistake is in assuming that & when construction is sort of if -like thing of C-like languages. But it's not, & {} is just a plain CSS ruleset (just like div {} for example) with & as its selector, and as a plain ruleset it does not expose any internal variables to outer scopes.

Only mixins expose their internals to the outer scope when invoked, so one of the methods to achieve what you need is:

@list: #000, #fff;
div {
  .custom-colors(@list, 0%, 20%, true);   
   color: @gradient;
}

.custom-colors(@value, @light, @dark, @lightdark) when (@lightdark = true) {
    @gradient: lighten(extract(@value, 1), @light), 
                darken(extract(@value, 2), @dark);
}    
.custom-colors(@value, @light, @dark, @lightdark) when (@lightdark = false) {
    @gradient:  darken(extract(@value, 1), @dark), 
               lighten(extract(@value, 2), @light);
}

That can be further simplified to:

@list: #000, #fff;
div {
  .custom-colors(@list, 0%, 20%, true);   
   color: @gradient;
}

.custom-colors(@value, @light, @dark, true) {
    @gradient: lighten(extract(@value, 1), @light),         
                darken(extract(@value, 2), @dark);
}    
.custom-colors(@value, @light, @dark, false) {
    @gradient:  darken(extract(@value, 1), @dark),  
               lighten(extract(@value, 2), @light);  
}

Also note that darken(somecolor, somevalue) is equal to lighten(somecolor, -somevalue) and vice-versa, so the whole thing can be further optimized depending on the actual snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM