构建目标的 LESS if 语句

LESS if statement for build targets

我在 LESS 中寻找能够更改一个变量并让它更改一堆不同变量的功能,这样我就可以更改我的编译目标并让它轻松更改大量变量。

这是我正在寻找的示例。唯一的问题是因为我在 .compile_for_if 中重新定义了 @img 它在另一个范围内。

@compile_for: "endpoint1";

@img_endpoint1: "./myImg.png";
@img_endpoint2: "https://somewhere.com/myImg.png";
@img: "./default.png";
.compile_for_if
{
    & when (@compile_for = "endpoint1")
    {
        @img: @img_endpoint1;
    }
    & when (@compile_for = "endpoint2")
    {
        @img: @img_endpoint2;
    }
}

... somewhere else ...

.img
{
    background-image:url("@{img}");
}

您可以通过将所有规则包含在无名命名空间 (&{...}) 中,然后在其范围内调用您的 .compile_for_if mixin 来实现此目的。这会将 .compile_for_if 中设置的所有变量暴露到命名空间中,因此所有规则都可以访问它。 (注意: 您还必须像下面给出的那样更改您的 .compile_for_if 定义。)

@compile_for: "endpoint1";

@img_endpoint1: "./myImg.png";
@img_endpoint2: "https://somewhere.com/myImg.png";
@img: "./default.png";

/* Added another set of conditional variables to illustrate */
@padding1: 10px;
@padding2: 20px;
@padding: 5px;

.compile_for_if when (@compile_for = "endpoint1"){
  @img: @img_endpoint1;
  @padding: @padding1;  

}
.compile_for_if when (@compile_for = "endpoint2"){
  @img: @img_endpoint2;
  @padding: @padding2;
}

&{
  .compile_for_if();
  .img{
    background-image:url("@{img}");
  }

  div{
    padding: @padding;
  }
}