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

大憨熊 提交于 2019-12-08 23:34:28

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;
  }
}

As of recently it is possible to do this, but it's a very recent feature and does depend on the version of Sass you're using. (I have it working using latest dart-sass)

Syntax is like this

@mixin test-mixin() { 
  $var: 10px;
  @content($var);
}

@include test-mixin() using ($var) {
  margin-top: $var;
}

You can pass multiple variables through to the content block, but there are some caveats.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!