3

By using LESS, I am trying to execute a conditional inside a mixing

Here is my code

.my-mixing (@isInverse) {
    .navbar {
        when(@isInverse) {
            .navbar-inverse;
        }
    }
}

.my-mixing(true);

it does not work.
Any hints?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Lorraine Bernard
  • 13,000
  • 23
  • 82
  • 134

2 Answers2

3

You can't use when in the way you are trying to, it always has to appear after in the mixin-declaration. And you have to provide a fallback mixin, if the variable does not match the guard.

.my-mixing (@isInverse) {
    .navbar {
       .navbar-inverse(@isInverse);         
    }
}

.navbar-inverse(@a) when(@a){
   /* do something if it matches */
}
.navbar-inverse(@a) when not(@a){
  /* do something else (or nothing at all) */
}

.my-mixing(true);

I added when not(@a) in the second mixin, so it won't get included per se. You could as well place it before the guarded mixin to prevent styles from being overridden.

Christoph
  • 50,121
  • 21
  • 99
  • 128
2

Given the following html...

<div class="navbar">
    I am navbar!
</div>

this is a working solution:

.navbar-inverse(@isInverse){
    // do nothing or whatever
}
.navbar-inverse(@isInverse) when(@isInverse){
    // apply styles for inverse navbar
}

.my-mixin(@isInverse){
    .navbar{
        .navbar-inverse(@isInverse);
    }
}
.my-mixin(true);

But if you would have shown your html and specified your problem more precisely maybe there would be a more suiting solution.

tsterker
  • 310
  • 1
  • 4
  • 12
  • note: @Christoph uses the guard-order that conforms to the [documentation](http://lesscss.org/#-pattern-matching-and-guard-expressions) but in practice it didn't work for me that way. – tsterker Oct 15 '12 at 16:47
  • That's interesting, I tried it [here](http://winless.org/online-less-compiler) and it worked. Normally the order should not matter. – Christoph Oct 15 '12 at 16:58
  • Very confusing... now I also tested it at [winless.org](http://winless.org/online-less-compiler) and your solution resolves to the **false-case on either input** (true/false). (Meaning that in the css output the false-case is always the *last in order*, thus overwriting previous styles.) Am I missing something? – tsterker Oct 15 '12 at 17:33
  • 1
    True, a `when not(@a)` condition is needed if there are styles that can be overridden. – Christoph Oct 15 '12 at 18:12
  • Thanks for the hint - I edited my answer to reflect or conversation. And I +1ed you answer (already yesterday) because your inverted order has a little less fuzz;) – Christoph Oct 16 '12 at 07:47