SASS/SCSS object key value loop [duplicate]

你离开我真会死。 提交于 2019-12-05 11:53:00

问题


Take a look at this example:

@include font-face('Entypo', font-files('entypo.woff'));

.icon {
  display: inline;
  font: 400 40px/40px Entypo;
}

.icon-star {
  @extend .icon;

  &:after {
    content: "\2605";
  }
}

.icon-lightning {
  @extend .icon;

  &:after {
    content: "\26A1";
  }
}

I want to make things as DRY as possible so I want to know if the following is possible, and if so how?

@include font-face('Entypo', font-files('entypo.woff'));

.icon {
  display: inline;
  font: 400 40px/40px Entypo;
}

$icons {
  $star: "\2605";
  $lightning: "\26A1";
}

@each $icon in $icons {
  $key = $icon{key}; // ???
  $value = $icon{value}; // ???

  .icon-#{$key} {
    @extend .icon;

    &:after {
      content: $value;
    }
  }
}

回答1:


Sass does not currently support mappings. You'll have to live with lists of lists for now.

$icons: star "\2605", lightning "\26A1";

@each $icon in $icons {
  $key: nth($icon, 1);
  $value: nth($icon, 2);

  .icon-#{$key} {
    @extend .icon;

    &:after {
      content: $value;
    }
  }
}



回答2:


Sass 3.3 (released on 2014/03/07) now allows you to use maps :

@include font-face('Entypo', font-files('entypo.woff'));

.icon {
  display: inline;
  font: 400 40px/40px Entypo;
}

$icons: (
  star: "\2605",
  lightning: "\26A1"
);

@each $key, $value in $icons {
  .icon-#{$key} {
    @extend .icon;

    &:after {
      content: $value;
    }
  }
}


来源:https://stackoverflow.com/questions/16083292/sass-scss-object-key-value-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!