简体   繁体   English

@each 在 Map 上的循环不会用值替换变量,而是在 SASS 中打印变量名

[英]@each loop over Map doesn't replace variable with value but prints variable name instead in SASS

I have some colors in a map:我在 map 中有一些 colors:

$colors: (
  a: #fff,
  b: #000,
)

Now I want to create CSS variables from that map:现在我想从 map 创建 CSS 变量:

:root {
  @each $name, $color in $colors {
    @debug($color);
    --color-#{$name}: $color;
  }
}

This looks pretty much like the textbook example.这看起来很像教科书的例子。 It does indeed create variables and debug shows the correct values (like #fff ).它确实创建了变量并且调试显示了正确的值(如#fff )。 Unfortunately in the CSS it comes out like:不幸的是,在 CSS 中,结果如下:

--color-a: $color;
--color-b: $color;

What did I wrong?我做错了什么?


PS: This happens on an Angular 8 project. PS:这发生在 Angular 8 项目上。

You could use interpolation syntax also for $color :您也可以对$color使用插值语法:

$colors: (
  a: #fff,
  b: #000,
);

:root {
  @each $name, $color in $colors {
    --color-#{$name}: #{$color};
  }
}

Your result:你的结果:

:root {
  --color-a: #fff;
  --color-b: #000;
}

Edit: why it is needed here?编辑:为什么这里需要它?

That's a very good question, cause I really didn't know why .这是一个很好的问题,因为我真的不知道为什么 So I did some research and I found this interesting doc=> https://sass-lang.com/documentation/breaking-changes/css-vars where is written:所以我做了一些研究,发现这个有趣的文档=> https://sass-lang.com/documentation/break-changes/css-vars写在哪里:

To provide maximum compatibility with plain CSS, more recent versions of Sass require SassScript expressions in custom property values to be written within interpolation.为了提供与普通 CSS 的最大兼容性,Sass 的更新版本要求将自定义属性值中的 SassScript 表达式写入插值中。 Interpolation will also work for older Sass versions, and so is recommended for all stylesheets.插值也适用于较旧的 Sass 版本,因此建议用于所有样式表。

So the difference is because you are using custom property values ( --color-a ) and not a normal CSS property like content所以区别在于您使用的是自定义属性值( --color-a )而不是普通的 CSS 属性,如content

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM