Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

less - Conditionally setting one variable's value based on another

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

In other words I need a Less equivalent of the JS code:

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

I've tried to accomplish this using when function, but from what I understand it doesn't work that way and is only applicable to CSS properties, not variables:

when (@side = right){
  @sideOpposite: left;
}
when (@side = left){
  @sideOpposite: right;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See Mixin Guards and Ruleset Guards (aka "CSS Guards") for when usage examples. Since you need to define a variable you'll have to use mixin-based condition (rulesets do not expose their variables to an outer scope). E.g.:

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

(Use any suitable mixin name instead of .-, e.g. .define-opposite-side).


And with Argument Pattern Matching it can be further simplified just to:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...