How to use the LESS "when" operator?

Asked

Viewed 81 times

2

I quickly searched the site of Less to see how it is used, but I was not successful, so I wanted to know how the operator works when less!?

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 it works?

(Optional) If you know where operator documentation like when on LESS, could you inform me? Thank you!

2 answers

1

  • Exactly, and it works like a loop. Even after your css is interpreted, if the condition inside when turns true at some point, then it will call the mixin that is set to it

1


The name of this resource is guarded mixins, and serves to test expressions, similar to the existing conditional structures in various languages. However, instead of if/else, Less does this with the keyword when.

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() for true, the first rule will be compiled. Otherwise mixin will be ignored. However as there is another mixin with the same name, it will be tested as well and if the return of isnumber() is true, this will be compiled. If both conditions are false, the rule will be dropped.

/* 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 */ 
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.