I am new to Less and trying to convert some SCSS mixins over. However, I am having some problems with optional parameters. For example:
.border(@border; @block: null; @blockEnd: null) {
border: @border;
border-block-end: if(@blockEnd, @blockEnd, @block);
}
.container {
.border(@border: 1px solid red);
}
This results in the following CSS:
.container {
border: 1px solid red;
border-block-end: ;
}
Notice that border-block-end
is still generated, but with an empty value.
How can I set mixin parameters to optional, as in undefined
and only generate the CSS property if that parameter exists?
Target Output
// LESS
.container {
.border(@border: 1px solid red);
}
// Would generate CSS...
.container {
border: 1px solid red;
// Only generates properties with a value
}
Looks like I am able to leverage the Mixin Guards. By using the when not
and if not
operators nested inside the mixin, I can check for multiple parameters where the ,
separator acts as an or
.
When @blockEnd or @block are truthy, compile the following
.border(@border; @block: null; @blockEnd: null;) {
border: @border;
& when not(@blockEnd = null), not(@block = null) {
border-block-end: if(not (@blockEnd = null), @blockEnd, @block);
}
}
This will evaluate to:
// LESS
.container {
.border(@border: 1px solid red);
}
// CSS
.container {
border: 1px solid red;
}
It feels quite verbose, but it gets the job done.. Am I missing an easier approach, possibly?