LESS conditional variable change inside mixin

北城余情 提交于 2019-12-11 12:08:53

问题


I need to achieve such effect, but even when @padding actually < @height it still use multiplier value 2, which is non-sense...Is there any limitation i don't know about?

.btn-svg-offset(@height, @padding) {
    @paddings-n: floor(@height / @padding);
    @multiplier: 2;

    & when (@padding < @height) {
        @multiplier: 1;
    }

    @btn-svg-offset: @padding + ((@height / @multiplier) * @paddings-n);
};

Any workarounds are welcome)


回答1:


& when is not if (they usually say so just for short). & {...} is still a regular ruleset with its own scope, and variables defined inside a ruleset are not visible in outer scopes.

To achieve what you need, rewrite this using conditional mixins (mixin's internals (incl. variables) are actually expanded into the caller scope):

.btn-svg-offset(@height, @padding) {
    @paddings-n: floor(@height / @padding);

    .-() {@multiplier: 2} .-;
    .-() when (@padding < @height) {
        @multiplier: 1;
    }

    @btn-svg-offset: @padding + ((@height / @multiplier) * @paddings-n);
}

Note that you can put the same condition onto the .btn-svg-offset mixin itself (so in real code it does not have to be that verbose as in my example... Exact code may vary though depending on the mixin usage and its other internals).

(Upd.) For example the following code (certain variations are possible too) would be an equivalent:

.btn-svg-offset(@height, @padding, @multiplier: 2) {
    @paddings-n: floor(@height / @padding);
    @btn-svg-offset: @padding + @height / @multiplier * @paddings-n;
}

.btn-svg-offset(@height, @padding) when (@padding < @height) {
    .btn-svg-offset(@height, @padding, 1);
}


来源:https://stackoverflow.com/questions/29496933/less-conditional-variable-change-inside-mixin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!