Conditionally encapsulate rules

2019-07-14 02:58发布

问题:

Let's say I have the following:

@import 'hello.less'

Based on a variable value, I want to nest this inside another class. The following is what I want to accomplish, in pseudocode:

if(@someVar = true):
  .someClass {
    @import 'hello.less'
  }
else:
  @import 'hello.less'

I guess I could use mixin guards, but I don't know how to handle the 'else' case:

.someClass when (@someVar = true) {
  @import 'hello.less'
}

// Else?

回答1:

Using not and &(& expands to nothing if its parent is the global scope (e.g.)):

@some-var: true;

.some-class when (@some-var) {
    @import (multiple) "hello";
}

& when not(@some-var) {
    @import (multiple) "hello";
}

Note that multiple import option is required in this case since both imports are always evaluated and the guards only control if the content appears in output or not.

---

Though in general I wonder why you need to keep the code for different projects in the same file and control its compilation indirectly via variables. Instead I'd suggest to create just "namespaced hello" file:

.some-class {@import "hello";}

and import it unconditionally in the project you want it that way.



回答2:

My current solution is as follows:

@someVar: true;

.someClass when (@someVar = true) {
  .main(false);
}

.main(@someVar);

.main(@x) when not (@x) {
  @import 'hello.less'
}

I'll mark this as the answer unless someone has a better one.



标签: less