kleinfreund
kleinfreund

Reputation: 6806

SASS mixin with boolean variable: If-Statement not working

I'm creating a mixin which styles an $element's $property to generate page-specific CSS. (Background: There are four pages with different color schemes).

Not working mixin (with if-statement):

@mixin themify($element, $property, $color-light: false) {
     @if $color-light == "true" {
         $pages: home forestGreen, about darkOrange, work dodgerBlue, contact fireBrick;
     }
     @else {
         $pages: home darkGreen, about orange, work royalBlue, contact crimson;
     }
     @each $page in $pages {
         .page--#{nth($page, 1)} .#{$element} {
             #{$property}: nth($page, 2);
         }
     }
 }

 /* Call the mixin */
 @include themify(site-nav, background-color, $color-light: true);

Error:

error/style.scss (Line 47 of css/ui/_misc.scss: Undefined variable "$pages".)

Update

Adding $pages: ""; before the if-statement helps. Why?

Upvotes: 15

Views: 20128

Answers (3)

Martin Turjak
Martin Turjak

Reputation: 21234

You need to have a default $pages defined outside the @if clause.
It is a scope issue ... the @if clause is a narrower scope than your mixin ... so anything defined inside would be private to that scope.

Try it like this:

@mixin themify($element, $property, $color-light: false) {
    $pages: ();
    @if $color-light == true { // boolean check not string
        $pages: home forestGreen, about darkOrange, work dodgerBlue, contact fireBrick;
    }
    @else {
        $pages: home darkGreen, about orange, work royalBlue, contact crimson;
    }
    @each $page in $pages {
        .page--#{nth($page, 1)} .#{$element} {
            #{$property}: nth($page, 2);
        }
    }
}

/* Call the mixin */
@include themify(site-nav, background-color, $color-light: true);

DEMO

Upvotes: 27

vlasterx
vlasterx

Reputation: 3856

I have made a small function to check boolean properly (for myself at least)

http://www.sassmeister.com/gist/a72a18f259c9c18ab773300b197bd08a

  // ----
  // libsass (v3.3.6)
  // ----

  // CHECK BOOLEAN VALUE
  @function bool($value: false) {
      @if $value == false or 
          $value == "" or 
          $value == "false" or 
          $value == 'false' or
          $value == 0 {
              @return false;
          }
      @return true;
  }


  // Lets test
  $var1: false;

  @if bool($var1) == true {
    /* This value is true */
  } @else {
    /* This value is false */
  }

Upvotes: 0

Wojciech Bednarski
Wojciech Bednarski

Reputation: 6373

Message error could be confusing, but you have syntax error. It should be @else not else.

Upvotes: 1

Related Questions