1

How to get mixin argument from array variable in a loop with Sass? Example code is below:

$colors: red green blue;
    $red-foo: 100px;
    $red-bar: 110px;
    $red-baz: 120px;
    $green-foo: 100px;
    $green-bar: 110px;
    $green-baz: 120px;
    $blue-foo: 100px;
    $blue-bar: 110px;
    $blue-baz: 120px;
    
    @mixin item($color-foo, $color-bar, $color-baz){
        width: $color-foo,;
        height: $color-bar;
        ...
    }
    
    @each $color in $colors {
        .class-#{$color}{
            @include item($color#{-foo}, $color#{-bar}, $color#{-baz})
        }
    }

Desired output is below:

    .class-red{
        //variables
    }
    
    .class-green{
        //variables
    }
    
    .class-blue{
        //variables
    }

Also is there a way for shorthand of $color-foo, $color-bar, $color-baz like @include item($color-shorthand)? Maybe there could be a better solution for this.

1 Answer 1

5

You want Sass Maps

$colors: (
    red: (
        foo: 100px,
        bar: 110px,
        baz: 110px
    ),
    green: (
        foo: 200px,
        bar: 210px,
        baz: 220px
    ),
    blue: (
        foo: 300px,
        bar: 310px,
        baz: 320px
    )
);

@mixin item ($color-foo, $color-bar, $color-baz) {
    width: $color-foo;
    height: $color-bar;
    padding: $color-baz;
}

@each $name, $value in $colors {
    .class-#{$name} {
        @include item(
            map-get($value, foo),
            map-get($value, bar),
            map-get($value, baz)
        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.