SASS ignores variables, defined in if-statement

别等时光非礼了梦想. 提交于 2020-01-09 07:15:47

问题


I have one file named style.scss with the following code:

@import 'variables';

body {
    color: $text-color;
    background: $background-color;
}

And one partial named _variables.scss:

$colorscheme: white;

@if $colorscheme == white {
    $text-color: #333;
    $background-color: #fff;
}
@else {
    $text-color: #ccc;
    $background-color: #333;
}

The if-statement works properly, but the variables defined inside, do not work. When I try to compile it, I keep getting:

Syntax error: Undefined variable: “$text-color”.


回答1:


That's completely expected. Variables have a scope to them. If you define them inside of a control block (like an if statement), then they won't be available outside. So, what you need to do is initialize it outside like so:

$text-color: null;
$background-color: null;
@if $colorscheme == white {
    $text-color: #333;
    $background-color: #fff;
}
@else {
    $text-color: #ccc;
    $background-color: #333;
}

Or...

$text-color: #ccc;
$background-color: #333;
@if $colorscheme == white {
    $text-color: #333;
    $background-color: #fff;
}

Though it would be less verbose to use the if() function like this:

$text-color: if($colorscheme == white, #333, #ccc);
$background-color: if($colorscheme == white, #fff, #333);



回答2:


While this example is even more verbose, it eliminates the need to set two empty variables:

@if $colorscheme == white {
  $text-color: #333 !global;
  $background-color: #fff !global;
} @else {
  $text-color: #ccc !global;
  $background-color: #333 !global;
}

@cimmanon's 2nd and 3rd examples are much better, though.



来源:https://stackoverflow.com/questions/15371332/sass-ignores-variables-defined-in-if-statement

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