@ each-loop使用map-get()

时间:2018-11-03 08:43:26

标签: sass

我正在尝试使用> map-get() @ each-loop 来执行此操作代码,但出现错误,请帮忙。

$names: (
    (
        "name": "name-1",
        "filename": "name-1.jpg",
        "color": "blue",
    ),

    (
        "name": "name-2",
        "filename": "name-2.jpg",
        "color": "red",
    )
);

@each $name in $names {
    $name: map-get($names, "name");
    $filename: map-get($names, "filename");
    $color: map-get($names, "color");

    .#{$name} {
        background-image: url("#{$filename}");
        color: $color;
    }
}

2 个答案:

答案 0 :(得分:1)

您的$names列表不需要键。您可以在遍历嵌套列表时定义变量键,也不必将其括在引号中,就好像它们是strings一样。在@each循环中,一旦定义了列表中的每个变量键,就可以使用方括号内的每个变量。

//-Updated SASS List, included list in name to make it more clear.
$names-list: (
  (
    name-1,
    name-1,
    blue
  ),

  (
    name-2,
    name-2,
    red
  )
);

//-Updated @each loop, defined variable keys for each item in the list.
@each $name, $fileName, $color in $names-list {
    .#{$name} {
       background-image: url('#{$fileName}.jpg');
       color: color;
     }

 }
 //-The code above compiles to the following CSS Classes with the properties defined inside
 .name-1 {
     background-image: url("name-1.jpg");
    color: color;
  }

 .name-2 {
   background-image: url("name-2.jpg");
   color: color;
  }

答案 1 :(得分:1)

由于没有循环实图(http://sass-lang.com/documentation/file.SASS_REFERENCE.html#maps),您会收到该错误。

您可以使用嵌套地图来解决您的问题。像这样:

$names: (
    layout-1: (
        name: "name-1",
        filename: "name-1.jpg",
        color: blue
    ),

    layout-2: (
        name: "name-2",
        filename: "name-2.jpg",
        color: red
    )
);


@each $key, $value in $names {
  .#{map-get($value, name)} {
    background-image: url("#{map-get($value, filename)}");
    color: map-get($value, color);
  }
}