Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to convert numbers into words, so:

  • "1-3" -> "one-third"
  • "3-3" -> "three-thirds"
  • "2-5" -> "two-fifths"

The numbers are generated in a loop, which should output a bunch of different class names like one-third or one-half:

$number = 3;

@for $i from 1 through $number-1 {
    // some calculations to output those classes: ".one-third", ".two-thirds"

    // The following currently outputs class names like ".1-3" and ".2-3"
    .#{$i}-#{$number} {
        // CSS styles
    }
}

I think I need to use two different associative arrays, which in PHP (just as an example) might look like:

$1 = array( 
   "1"=>"one", 
   "2"=>"two", 
   "3"=>"three" 
);

$2 = array( 
   "1"=>"whole", 
   "2"=>"half", 
   "3"=>"third" 
);

Is it possible in SASS/SCSS to create associative arrays at all or is there any workaround?

question from:https://stackoverflow.com/questions/21344891/associative-array-scss-sass

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

1 Answer

In Sass < 3.3 you can use multidimensional lists:

$numbers: (3 "three") (4 "four");

@each $i in $numbers {
    .#{nth($i,2)}-#{nth($i,1)} {
        /* CSS styles */
    }
}

DEMO

In Sass >= 3.3 we get maps:

$numbers: ("3": "three", "4": "four");

@each $number, $i in $numbers {
    .#{$i}-#{$number} {
        /* CSS styles */
    }
}

DEMO


So in terms of fractions, you could just do something in this direction, so that you don't need multiple lists or maps:

$number: 6;
$name: (
    ("one"),
    ("two" "halv" "halves"),
    ("three" "third" "thirds"),
    ("four" "quarter" "quarters"),
    ("five" "fifth" "fifths"),
    ("six" "sixth" "sixsths")
);

and then whatever you want to do with your loops ... maybe even something like this =D

@for $i from 1 to $number {
  @for $j from 2 through $number {
    .#{ nth( nth( $name, $i ), 1 ) }-#{
      if( $i>1,
        nth( nth( $name, $j ), 3 ),
        nth( nth( $name, $j ), 2 )
      )} {
        /* CSS styles */
    }
  }
}

DEMO

(I wrote it this way so that you can notice in @for, that using to goes to n - 1)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...