Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SASS mixin with boolean variable: If-Statement not working

Tags:

scope

sass

mixins

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?

like image 908
kleinfreund Avatar asked Jan 25 '14 12:01

kleinfreund


2 Answers

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

like image 157
Martin Turjak Avatar answered Oct 19 '22 05:10

Martin Turjak


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

like image 38
Wojciech Bednarski Avatar answered Oct 19 '22 06:10

Wojciech Bednarski