如何一次处理多个SASS地图?

时间:2019-09-24 19:46:14

标签: css function sass flexbox maps

我正在尝试动态创建实用程序类。

可以在SASS中定义地图,然后在@each处使用,以基于地图的keyvalue生成类。但是,需要在property中手动添加css @each。我想要一个可以添加该元素和一些基于地图数据的命名约定的函数。因此,基于以下示例,我想动态添加flex-direction,而不必为每个地图创建一个@each

有效的方法

//Example Map
@flex-wrap: ("nw": "no-wrap", "w": "wrap", "wr": "wrap-reverse")

//Example @each
@each $name, $value in $flex-wrap
    .flx-w-#{$name}
        flex-direction: #{$value}

我需要的

.flx + $prefix + $name
    $property: $value

以及预期的已编译CSS结果

.flx-d-w {
    flex-direction: wrap;
}

1 个答案:

答案 0 :(得分:0)

一种执行所需操作的动态方法是使用嵌套映射,两个@each循环和一个mixin。

$flex-direction: (
  "name": "flex-direction",
  "prefix": "flx-d",
  "values": (
    "r": "row",
    "c": "column",
    "rr": "row-reverse",
    "cr": "column-reverse"
  )
);

$flex-wrap: (
  "name": "flex-wrap",
  "prefix": "flx-w",
  "values": (
    "nw": "nowrap",
    "w": "wrap",
    "wr": "wrap-reverse"
  )
);

@mixin createClasses($maps...) {
  @each $map in $maps {
    $propertyName: map-get($map, "name");
    $propertyPrefix: map-get($map, "prefix");

    @each $value, $key in map-get($map, "values") {
      .#{$propertyPrefix}-#{$value} {
        #{$propertyName}: #{$key};
      }
    }
  }
}

@include createClasses($flex-direction, $flex-wrap);

使用上面的示例,您将获得:

.flx-d-r {
  flex-direction: row;
}

.flx-d-c {
  flex-direction: column;
}

.flx-d-rr {
  flex-direction: row-reverse;
}

.flx-d-rc {
  flex-direction: column-reverse;
}

.flx-w-nw {
  flex-wrap: nowrap;
}

.flx-w-w {
  flex-wrap: wrap;
}

.flx-w-wr {
  flex-wrap: wrap-reverse;
}

这里的“魔术”部分是使用扩展...运算符在mixin(documentation here)中传递任意数量的地图。您只需在所有地图上调用一次,它将创建您所有的类。


SASS版本的代码:

$flex-direction: ("name": "flex-direction", "prefix": "flx-d", "values": ("r": "row", "c": "column", "rr": "row-reverse", "cr": "column-reverse"))
$flex-wrap: ("name": "flex-wrap", "prefix": "flx-w", "values": ("nw": "nowrap", "w": "wrap", "wr": "wrap-reverse"))

=createClasses($maps...)
  @each $map in $maps
    $propertyName: map-get($map, "name")
    $propertyPrefix: map-get($map, "prefix")
    @each $value, $key in map-get($map, "values")
      .#{$propertyPrefix}-#{$value}
        #{$propertyName}: #{$key}

+createClasses($flex-direction, $flex-wrap)