LoginSignup
9
7

More than 5 years have passed since last update.

Sassのif文で変数の代入

Last updated at Posted at 2014-06-14

以下のコードでエラー。

@each $type in "facebook" "twitter" {
  .#{$type} {
    @if $type == "facebook" {
      $button: "button_like.png";
    } @else if $type == "twitter" {
      $button: "button_tweet.png";
    }
    width: image-width($button);
    height: image-height($button);
    background-image: image-url($button);
    background-repeat: no-repeat;
  }
}

if文には必ず入っていて、$buttonに代入されているはずなのに、
Undefined variable
と言われます。

これは、$buttonのスコープがif文の中に入っていて、if文の後に書いた$buttonがスコープ外になってしまうから。

以下のように、if文のスコープの外で一回代入すれば解決。

@each $type in "facebook" "twitter" {
  .#{$type} {
    $button: "";
    @if $type == "facebook" {
      $button: "button_like.png";
    } @else if $type == "twitter" {
      $button: "button_tweet.png";
    }
    width: image-width($button);
    height: image-height($button);
    background-image: image-url($button);
    background-repeat: no-repeat;
  }
}

もっとちゃんとした書き方があるかもしれませんが。

9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7