4

I wonder if there is a better solution (or if my solution is even right), to create if statement like behavior with variables and guards.

Goal:

  • If variable is set to true, compile the code (works)
  • If variable is set to anything else, ignore the code (default, works)
  • Keep initial code position (dosnt work, is merged wherever .responsive (@responsive); is called)

My Code:

@responsive: true;

.responsive(true){
  a {
    color: red;
  }
}

.responsive(true) {
  b {
    color: blue;
  }
}

.responsive (@responsive);
InitArt
  • 97
  • 1
  • 1
  • 7

2 Answers2

5

I am not completely sure I understand what you say doesn't work.

But if I do ... there are two things connected to this that you have to bare in mind in LESS:

  • scope matters - not order (you can define a variable/mixin after you call it, as long as you deine it in the same scope or a scope that is accessible)
  • the mixin gets rendered where you call it not where you define it

that said - if you really want to use the same guard in multiple places to do different things, you would need to define multiple mixins (each place would get another mixin), and if you want to render it in the place you define it, you would just need to call it immediately after (or before) you define it. Something like this:

@responsive: true;

test1 {
  color:green;
}

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

test2 {
  color:green;
}


.b() when (@responsive) {
  b {
    color: blue;
  }
}
.b;

the output will be:

test1 {
  color: green;
}
a {
  color: red;
}
test2 {
  color: green;
}
b {
  color: blue;
}

So the mixins .a() and .b() are returned if @responsive is set to true, if not you get:

test1 {
  color: green;
}
test2 {
  color: green;
}

I hope this is kinda what you wanted.

fmsf
  • 36,317
  • 49
  • 147
  • 195
Martin Turjak
  • 20,896
  • 5
  • 56
  • 76
  • That's it, easy and logical, thank you very much. I've already expected that it isn't possible to do php like if statements. – InitArt May 27 '13 at 21:18
  • The key to his is making sure that after you've declared the mixin `.b() when (@responsive)` you also call the mixin `.b();`. – Erik Philips Sep 13 '18 at 18:19
3

I ended up using this:

@responsive: true;

section.content {
  .responsive () when (@responsive) {
    @media (min-width: 768px) {
      float: right;
      width: 80%;
    }
    @media (min-width: 980px) {
      width: 60%;
    }
  }
  .responsive;
}

aside.left {
  .responsive () when (@responsive) {
    @media (min-width: 768px) {
      float: left;
      width: 20%;
    }
  }
  .responsive;
}
InitArt
  • 97
  • 1
  • 1
  • 7