Sass manipulate with @content

Viewed 105

Is it possible to manipulate with @content magic variable in SASS? I would like to replace some stuff in here before output. Or maybe can I fill some variable with it?

The conclusion is that, I want to make an mixin @important that create both versions. Important, and no-important.

Input

.test {
  @include important {
    color: red;
    text-align: left;
  }
}

Expected output

.test {
  color: red;
  text-align: left;
}
.test-i {
  color: red !important;
  text-align: left !important;
}
1 Answers

No, you can't. But I quickly wrote you a mixin to make it work. It doesn't accepts multiple properties (yet).

First Note: I changed the mixin it now does accept multiple properties. Here is the Codepen.

Second Note: I updated the mixin adding multiple properties does no longer compile to different classes for each property, instead you get two versions, one without the !important suffix and one with.

This is the mixin:

@function return($state) {
  @return if($state == '', '', '-i');
}

@mixin loop($name, $items...) { 
  @each $item in $items / 2 {   
    @each $state in ('', '!important') {
      $suffix: return($state);
      
      .#{$name}#{$suffix} { 
        @for $i from 1 through (length($items) / 2) { 
          #{nth($items, ($i * 2) - 1)}: #{nth($items, ($i * 2))} #{$state};
        }
      }
    }
  }
}

This is how you include it:

// @include loop([classname], [property], [value]);

@include loop(whateverClassname, color, red);

This is what it compiles to:

.whateverClassname {
  color: red ;
}

.whateverClassname-i {
  color: red !important;
}

This is what it now compiles to, when you use multiple properties at once:

@include loop(whateverClassname, color, red, background-color, green, display, flex);

.whateverClassname {
  color: red ;
  background-color: green ;
  display: flex ;
}

.whateverClassname-i {
  color: red !important;
  background-color: green !important;
  display: flex !important;
}

Conclusion: it works as expected and does no longer bloat your CSS.

Hope I could help you at least a little ;-)

Related