Creating or referencing variables dynamically in Sass

Krzysztof Romanowski picture Krzysztof Romanowski · Dec 16, 2011 · Viewed 83.5k times · Source

I'm trying to use string interpolation on my variable to reference another variable:

// Set up variable and mixin
$foo-baz: 20px;

@mixin do-this($bar) {
    width: $foo-#{$bar};
}

// Use mixin by passing 'baz' string as a param for use $foo-baz variable in the mixin
@include do-this('baz');

But when I do this, I get the following error:

Undefined variable: "$foo-".

Does Sass support PHP-style variable variables?

Answer

dibbledeedoo picture dibbledeedoo · Jun 23, 2015

This is actually possible to do using SASS maps instead of variables. Here is a quick example:

Referencing dynamically:

$colors: (
  blue: #007dc6,
  blue-hover: #3da1e0
);

@mixin colorSet($colorName) {
    color: map-get($colors, $colorName);
    &:hover {
        color: map-get($colors, $colorName#{-hover});
    }
}
a {
    @include colorSet(blue);
}

Outputs as:

a { color:#007dc6 }
a:hover { color:#3da1e0 }

Creating dynamically:

@function addColorSet($colorName, $colorValue, $colorHoverValue: null) {
  $colorHoverValue: if($colorHoverValue == null, darken( $colorValue, 10% ), $colorHoverValue);

  $colors: map-merge($colors, (
    $colorName: $colorValue,
    $colorName#{-hover}: $colorHoverValue
  ));

  @return $colors;
}

@each $color in blue, red {
  @if not map-has-key($colors, $color) {
    $colors: addColorSet($color, $color);
  }
  a {
    &.#{$color} { @include colorSet($color); }
  }
}

Outputs as:

a.blue { color: #007dc6; }
a.blue:hover { color: #3da1e0; }
a.red { color: red; }
a.red:hover { color: #cc0000; }