Conditionally encapsulate rules

淺唱寂寞╮ 提交于 2019-12-24 06:27: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?

回答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.



来源:https://stackoverflow.com/questions/32212979/conditionally-encapsulate-rules

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!