SASS/SCSS object key value loop

onlineracoon picture onlineracoon · Apr 18, 2013 · Viewed 16.4k times · Source

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;
    }
  }
}

Answer

zessx picture zessx · Jul 22, 2014

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;
    }
  }
}