Conditionally setting one variable value based on another

I have a Less variable called @side . I want to set the @sideOpposite variable depending on the value of the @side variable. It can take only two values: "left" or "right."

In other words, I need a junior equivalent of JS code:

 var side = "left", sideOpposite = (side === "left")? "right" : "left"; 

I tried to accomplish this with the when function, but from the fact that, as I understand it, it doesn’t work this way and applies only to CSS properties, not to variables:

 when (@side = right){ @sideOpposite: left; } when (@side = left){ @sideOpposite: right; } 
+5
source share
3 answers

See Mixin Guardards and Rules Defenses (aka "CSS Guard") for when use them. Since you need to define a variable, you will have to use a condition based on mixin (the ruleset does not expose its variables to the outer scope). For instance:.

 .-(); .-() when (@side = right) { @sideOpposite: left; } .-() when (@side = left) { @sideOpposite: right; } 

(Use any suitable mixin name instead of .- , for example .define-opposite-side ).

---

And with Argument Pattern Matching it can be simplified simply:

 .-(@side); .-(left) {@sideOpposite: right} .-(right) {@sideOpposite: left} 
+10
source

I don’t know if I understand what you want to do, but from what I get about your question, you can do it with mixin. See Example

 //This is the mixin with default value .side(@leftORoposite: left) { float: @leftORoposite ;} 

Call this mixin when you need to leave it with .side(left) or when you need the right with .side(right) .

0
source

You can use the mix protection feature to enable conditional mixes.

 .mixin (@side; @sideOpposite) when (@side = right) { @sideOpposite: left } .mixin (@side; @sideOpposite) when (@side = left) { @sideOpposite: right } 
0
source

Source: https://habr.com/ru/post/1200226/


All Articles