Is there a way in LESS to remove a property if a variable does not exist?

Refresh

December 2018

Views

851 time

1

Lets say I have a LESS file like this...

@myVariable: 5px;

.myRule {
    myProperty1: @myVariable;
    myProperty2: myOtherValue1;
}

I'll get this outcome when I compile this with LESS.

.myRule {
    myProperty1: 5px;
    myProperty2: myOtherValue1;
}

However, instead of having @myVariable defined inside this LESS file, I want to reference it from somewhere else. My referenced file, may or may not contain this variable. Currently, if the variable is missing, I'll get a result like this.

.myRule {
    myProperty1: ;
    myProperty2: myOtherValue1;
}

Is there any LESS functionality that would allow me to remove the property completely if the variable was not provided so that my output was like this.

.myRule {
    myProperty2: myOtherValue1;
}

I've looked through the language features of LESS and couldn't find anything that does this. Maybe I'm missing something?

This would be the syntax that I'm imagining, but I'm pretty sure this doesn't exist.

.myRule {
    when(exists(@myVariable)) {
        myProperty1: @myVariable;
    }
    myProperty2: myOtherValue1;
}

2 answers

2

Set Default and Override

//Load in a master variable file for all LESS
//containing all "possible" variables that may be used
//but set to some default values that "hide" the properties
//if the variable does not exist (such as "false" here) 

@myVariable: false;

//Load in your specific variable references from elsewhere 
//Individual variable may/may not be defined in this file
//but if one is defiend, this value overrides the previous value

@myVariable: 5px;

//Define a mixin to activate the setting of the property
//only if the value is not the original default hiding value

.setIfValue(myVariable) when not (@myVariable = false) {
    myProperty1: @myVariable;
}

//Use the mixin to conditionally set the value into other mixins

.myRule {
    .setIfValue(myVariable);
    myProperty2: myOtherValue1;
}

Default Output

.myRule {
  myProperty2: myOtherValue1;
}

Overridden Output

.myRule {
  myProperty1: 5px;
  myProperty2: myOtherValue1;
}
1

I think you made the syntax too complex. It should be something like this:

.myRule {
    & when (@myVariable = false) {
      myProperty1: @myVariable;
    }
    myProperty2: myOtherValue1;
}

This feature (apparently) is called CSS Guards.

It seems like you can check if a variable has a specific value, but not whether this allows you to check for defined or not. So, I guess the other file should always define this variable as a prerequisite, but it can set it to 'false' (or any kind of default) to indicate that this property should not be used at all.