8

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;
}
Harry
  • 87,580
  • 25
  • 202
  • 214
zorza
  • 2,814
  • 3
  • 27
  • 41

3 Answers3

15

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}
Azametzin
  • 5,223
  • 12
  • 28
  • 46
seven-phases-max
  • 11,765
  • 1
  • 45
  • 57
0

I don't know if I've understand what you want to do, but from what I get about your question, you can do this with a mixin. See example

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

Invoke this mixin when you need it left with .side(left) or when you need right with .side(right).

Harry
  • 87,580
  • 25
  • 202
  • 214
hailton
  • 591
  • 1
  • 3
  • 15
  • 1
    This doesn't seem to match with the OP's requirement mate. OP wants something like a ternary operator's behavior. – Harry Apr 18 '15 at 10:46
0

You can take help of the mixin guard feature to allow conditional mixins

.mixin (@side; @sideOpposite) when (@side = right) { @sideOpposite: left }
.mixin (@side; @sideOpposite) when (@side = left) { @sideOpposite: right }
lessismore
  • 100
  • 2