3
votes

I'm trying to create a sass mixin that will take an undetermined number of items in a list as arguments in a mixin.

The end goal is to have a mixin that can be used to style the colors of different values for a progress bar (i.e. red when the bar has a low value). Here's what I came up with for the mixin:

@mixin progress-value($value..., $color...) {

    progress[value="#{$value}"] { 
        color: #{$color}; 

        &::-webkit-progress-value { background-color:  #{$color}; }
        &::-moz-progress-bar { background-color: #{$color}; }
    }   
}

// Calling the mixin
@include progress-value("0.25, #de2b23", "0.5, #FF8330", "0.75, #8A9F4A", "1, #14BB64");

I know this is a list I'm using with the include, but I'm not sure how to break that list up and pass it to each argument, or if this is even the best way to go.

I could create a simpler version of the mixin and call it for each value being styled, but that didn't seem very DRY.

Thanks for the help!

1

1 Answers

4
votes

You can try something like this:

@mixin make_progress($val,$col){
  progress[value="#{$val}"] {
    color: #{$col};
    &::-webkit-progress-value { background-color:  #{$col}; }
    &::-moz-progress-bar { background-color: #{$col}; }
  }  
}

@mixin progress-value($value-color...) {
    @each $progress in $value-color {
      @include make_progress(nth($progress,1),nth($progress,2));
    }
}

// Calling the mixin
@include progress-value(0.25 #de2b23);
// and with a multideimensional list
@include progress-value(0.5 #FF8330, 0.75 #8A9F4A, 1 #14BB64);

This will work now if you pass the parameters as a comma separated list of space separated pairs - value/color, like I did in the above example, or in some other way make clear that your list of parameters is multidimensional - like including each passed pair in parentheses:

// with a single parameter
@include progress-value((0.25, #de2b23));
// or with multiple parameters
@include progress-value((0.5, #FF8330), (0.75, #8A9F4A), (1, #14BB64));

I also made a separate mixin make_progress, for a better overview, and in case you would want to call it in some other instance outside the loop, but you could easily leave that inside the loop.

DEMO