Conditionally encapsulate rules

2019-07-14 02:41发布

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?

标签: less
2条回答
你好瞎i
2楼-- · 2019-07-14 03:11

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.

查看更多
地球回转人心会变
3楼-- · 2019-07-14 03:20

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.

查看更多
登录 后发表回答