在 SCSS 中循环两级嵌套列表以创建动态的@font-face

Loop two-level nested lists in SCSS to create a dynamic @font-face

我有一个这样的列表:

$fonts: (
  primary: (
    extra-light: (
      family:'Literata',
      weight: 200,
      style: normal,
      display: swap,
      src: url('/assets/fonts/Literata-Regular.woff2'),
    ),
    light: (
      family: 'Literata',
      weight: 300,
      style: normal,
      display: swap,
      src: url('/assets/fonts/Literata-Regular.woff2'),
    ),
    regular: (
      family: 'Literata',
      weight: 400,
      style: normal,
      display: swap,
      src: url('/assets/fonts/Literata-Regular.woff2'),
    ),
    bold: (
      family: 'Literata',
      weight: 700,
      style: normal,
      display: swap,
      src: url('/assets/fonts/Literata-Regular.woff2'),
    ),
  ),
  secondary: (
    light: (
      family: 'Zilla Slab',
      weight: 300,
      style: normal,
      display: swap,
      src: url('/assets/fonts/Zilla-Slab-Regular.woff2'),
    ),
    regular: (
      family: 'Zilla Slab',
      weight: 400,
      style: normal,
      display: swap,
      src: url('/assets/fonts/Zilla-Slab-Regular.woff2'),
    ),
    bold: (
      family: 'Zilla Slab',
      weight: 700,
      style: normal,
      display: swap,
      src: url('/assets/fonts/Zilla-Slab-Bold.woff2'),
    ),
),
  tertiary: (
    regular: (
      family: 'Montserrat',
      weight: 400,
      style: normal,
      display: swap,
      src: url('/assets/fonts/Montserrat-Regular.woff2'),
    ),
  ),
);

我的目标是遍历每种字体类型(primarysecondarytertiary),然后遍历每种变体(extra-lightlight , regular, bold) 每种类型。

我想根据每个字体数据构建动态@font-face 属性。

我尝试过类似的方法但没有成功:

@each $font-types in $fonts {
  $properties: family weight style src;

  @each $property, $values in $font-types {
    @if contains($properties, $property) {
      @font-face {
        @if $property != 'src' {
          font-#{$property}: map-get($font-properties, $property);
        } @else{
          src: map-get($font-properties, $property) format('woff2');
        }
      }
    }
  }
}

备案:contains 是辅助函数:

@function contains($list, $values...) {
  @each $value in $values {
    @if type-of(index($list, $value)) != 'number' {
      @return false;
    }
  }

  @return true;
}

对于那些可能有帮助的人:我最终使用了以下方法:

@each $font-type, $font-variants in $fonts {
  @each $properties, $font-variant in $font-variants {
    @font-face {
      @each $property, $value in $font-variant {
        @if $property != 'src' {
          font-#{$property}: $value;
        } @else {
          #{$property}: $value format('woff2');
        }
      }
    }
  }
}

输出如下: