Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

sass - Function to dynamically create classes from lists

Im fairly new to SASS and I'm confused by the way lists work. I have a multidimensional list like this:

$stylethemes: {
  (15, bold, red),
  (12, normal, blue)
}

I now want a function that makes a class for each list in $stylethemes and then puts the values of that list into that class. The output I want from the above list is this:

.theme1{
   font-size: 15;
   font-weight: bold;
   color: red;
}

.theme2{
   font-size: 12;
   font-weight: normal;
   color: blue;
}

Can anyone show me how I can do this? Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The code to produce the desired results would look like this:

$stylethemes: (
  (15, bold, red),
  (12, normal, blue)
);

@for $i from 1 through length($stylethemes) {
  .theme#{$i} {
    font-size: nth(nth($stylethemes, $i), 1);
    font-weight: nth(nth($stylethemes, $i), 2);
    color: nth(nth($stylethemes, $i), 3);
  }
}

However, you'll find this isn't particularly flexible. You're better off using mappings for the property/values so that you don't have to guarantee a specific order:

$stylethemes: (
  (font-size: 15, font-weight: bold, color: red),
  (font-size: 12, font-weight: normal, color: blue)
);

@for $i from 1 through length($stylethemes) {
  .theme#{$i} {
    @each $prop, $val in nth($stylethemes, $i) {
      #{$prop}: $val;
    }
  }
}

Or

$stylethemes: (
  theme1: (font-size: 15, font-weight: bold, color: red),
  theme2: (font-size: 12, font-weight: normal, color: blue)
);

@each $theme, $properties in $stylethemes {
  .#{$theme} {
    @each $prop, $val in $properties {
      #{$prop}: $val;
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...