The name of this feature is guarded mixins , and is used to test expressions , similar to the conditional structures existing in several languages. However, instead of if/else
, less does this with the when
keyword.
Taking the example of your question:
.box-shadow(@style, @c) when (iscolor(@c)){
-webkit-box-shadow: @style @c;
box-shadow: @style @c;
}
.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {
.box-shadow(@style, rgba(0, 0, 0, @alpha));
}
There are two ways to call .box-shadow()
and depending on the type of parameter, the rule will be compiled in a different way.
If the function returns iscolor()
is true
, the first rule is compiled. Otherwise, the mixin will be ignored. However, since there is another mixin with the same name, it will also be tested and returned by isnumber()
is true, it will be compiled. If both conditions are false, the rule will be discarded.
/* foo.less */
.meu-elemento {
.box-shadow(0 0 10px, red);
}
/* foo.css */
.meu-elemento {
-webkit-box-shadow: 0 0 10px red;
box-shadow: 0 0 10px red;
}
/* foo.less */
.meu-elemento {
.box-shadow(0 0 1px, 25%);
}
/* foo.css */
.meu-elemento {
-webkit-box-shadow: 0 0 10px rgba(0, 0, 0, 0.25);
box-shadow: 0 0 10px rgba(0, 0, 0, 0.25);
}
Examples of mixins ignored:
.meu-elemento {
.box-shadow(0 0 1px, "numero?"); /* tipo: string */
}
.meu-elemento {
.box-shadow(0 0 1px, url('foo/img.png')); /* tipo: url */
}