less.js: Allow guards to work with undefined variables

.guard () when (@variable) {
  a {
    color: red;
  }
}

Variable isn’t defined, therefore no output.

@variable: true;

.guard () when (@variable) {
  a {
    color: red;
  }
}

Variable is definied, therefore output:

a {
  color: red;
}

About this issue

  • Original URL
  • State: closed
  • Created 11 years ago
  • Comments: 46 (24 by maintainers)

Most upvoted comments

Has there been any movement on this request? I’ve been anxious for an undefined variable check for some time now. At the moment, I have a work around that is far from ideal…

p {
  & when not (@body-text-color = null) {
    color: @body-text-color;
  }
}

but, for this to work, the variable must exist and be defined as null by default. This would be far more effective/flexible if I could just instead check if the variable even exists in the first place.

What’s also happened since this was open is the if() function. So you can do color: if((@variable), green, red);

So… I skimmed back through this thread and I can’t really determine if this is mostly cases of people mis-understanding Less scope or not.

I don’t really see the need to check if vars are defined. Vars should be defined if they’re going to be consumed.

@import "library";  // contains @library-color: blue;

@library-color: red;

.box {
  color: @library-color;
}

I don’t understand the need to conditionally set a property based on the value changing. If the property is set to a variable, just change the variable’s value.

That is, if library.less has this:

@library-color: blue;
.box {
  color: @library-color;
}

All someone would need to do to set its output:

@import "library";
@library-color: red;

This would output:

.box {
  color: red;
}

Does the OP and others in that thread understand that behavior?

Not a big deal to add is-defined function (I expect it to appear in one of the first plugins as soon as v2 is released). Though to be honest the sad thing is that those who want this feature really miss the fact that both use-cases above are solvable (in many cases even with more compact code) w/o any feature like that.

@InitArt’s use-case:

// library.less
@variable: false;

a when (@variable) {
    color: red;
}

// ......................................
// user.less
@import "library.less"
@variable: true;

@nemesis13’s use-case:

// library.less
@base-color: green;
@menu-base-color: @base-color;

.menu {
    background-color: @menu-base-color;
}

// ......................................
// user.less
@import "library.less"
@base-color: white;
// or:
@menu-base-color: black;
// or whatever...

I.e. in summary: instead of testing if a variable is defined just provide a default value for that variable since variable values are freely overridable.