0

I try to loop through a map in SASS, but it's not working as expected.

Given the following list:

$names: (
  peter: (
    color: #f00,
    height: 20px,
    name: first
  ),
  susan: (
    color: #0f0,
    height: 40px,
    name: second
  )
);

I want to loop through it and create a CSS output like this:

.first {
  color: #0f0,
  height: 40px,
}

.second {
  color: #0f0,
  height: 40px,
}

To do that, I try to create a a mixin that loops through the map and outputs its values to CSS:

@mixin classes($map) {
  @each $key in $map {
    .#{map-get(map-get($key, $map), name)} {
      // Rules
    }
  }
}

@include classes($names);

Unfortunately the loop does not run, it quits with this error message:

$map: ("peter" (color: #f00, height: 20px, name: first)) is not a map for `map-get'

What am I doing wrong, is it not possible to nest calls to map-get?

1 Answer 1

6

The error should be a dead giveaway as to what is happening. Sass is interpreting your mapping as a list. This is happening because you're using the syntax for looping over a list, not a mapping. If you only pull a single value out of your mapping via @each, Sass casts it to a list.

@mixin classes($map) {
  @each $key, $val in $map {
    .#{map-get($val, name)} {
      // Rules
    }
  }
}
1
  • Thanks, it worked! I wasn't aware that this syntax is possible, but of course it makes sense.
    – Sven
    Aug 29, 2015 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.