How to use the "when" operator of LESS?

2

I gave a quick search on the less site to see how to use it, but I did not succeed, so I wanted to know how the LESS! operator works!

Examples:

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));
}

How does it work?

(Optional) If you know where the operator documentation such as when is in LESS, could you let me know? Thanks!

    
asked by anonymous 14.04.2016 / 15:59

2 answers

1

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 */ 
}
    
14.04.2016 / 17:10
1

When it works as if the mixin will only execute if the condition is true.

  

box-shadow (@style, @c) when (iscolor (@c))

The mixin will only run if the parameter @c is a color.

link

    
14.04.2016 / 16:52