SASS - Pass $variable to @content from within a @m

2019-08-04 23:54发布

问题:

I'm fighting to pass/get a $variable to a @content from within a @mixin. I read extensively online about it and know it's not possible. But maybe someone knows a good variation and/or other solution.

I created a SassMeister file to explain it: https://www.sassmeister.com/gist/f5404131ace6e243ef0a6c9cca042889

Anyone who can help me out? Thanks for reaching out ;-)

回答1:

I don't know if it is the best method, but you could create a global variable, change it at every loop and use it. Something like this:

$color-1: #333;
$color-2: #0073BD;
$myvariable:0;


$numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;

$orientations: left, right, top, bottom;

$breakpoints: (
  sm: 576px,
  md: 768px,
  lg: 992px,
  xl: 1200px,
);

@mixin breakpoint($breakpoint) {
  $breakpoint: map-get($breakpoints, $breakpoint);
  @media (min-width: $breakpoint) {
    @content;
  }
}

@mixin breakpoints($get-numbers: false) {
  @content;
  $breakpoints: map-keys($breakpoints);
  @each $breakpoint in $breakpoints {
    @include breakpoint($breakpoint) {
      @if $get-numbers == true {
        @each $number in $numbers {
          &-#{$number}-#{$breakpoint} {
            $myvariable: $number !global;
            @content;
          }
        }
      } @else {
        &-#{$breakpoint} {
          @content;
        }
      }
    }
  }
}

.u-margin {
  @include breakpoints(true) {
    content: "Test to get the #{$myvariable} variable";
    margin:$myvariable * 1rem;
    // How can I get the $number variable here?
    //margin: $number * 1rem;
  }
}