SASS / SCSS:从字符串/名称插入变量

Jak*_*ake 2 variables concatenation sass string-interpolation

是否可以按名称获取变量?

我尝试构建以下函数,但它没有按预期工作......

@function variable-lookup($variable, $suffix: "") {
  $value: null;
  @if ($suffix != "" and global-variable-exists($variable+"-"+$suffix)) {
    $value: #{$variable+"-"+$suffix};
  }
  @else if (global-variable-exists($variable)) {
    $value: #{$variable};
  }
  @return $value;
}
Run Code Online (Sandbox Code Playgroud)

这是一个如何使用它的示例:

$primary: #000;
$primary-hover: blue;

a {
  color: variable-lookup("primary", "base");

  &:hover {
    color: variable-lookup("primary", "hover");
  }
}
Run Code Online (Sandbox Code Playgroud)

当我想围绕这个“变量查找”函数编写一堆特定于上下文的速记包装函数时,真正的力量就会出现。

任何想法如何实现这一目标?

Bla*_*gma 5

尝试插入#{$variable+"-"+$suffix}以给出值primary-base并进一步尝试获取相同变量名称的值是不可能的primary-base已经是一个值并且不能被解释为变量名。这样的事情可能会导致很多混乱。

对于您想要完成的工作,最好使用 amap并检查key该地图中的

$colours: (
  'primary': red,
  'primary-base': blue
);

@function variable_lookup($colour, $suffix: '') {
  $value: null;
  @if ( $suffix != '' and map-has-key($colours, unquote($colour+'-'+$suffix)) ) {
    $value: map-get($colours, unquote($colour+'-'+$suffix));
  } @else if ( map-has-key($colours, unquote($colour)) ) {
    $value: map-get($colours, unquote($colour));
  }
  @return $value;
}

div {
  color: variable-lookup(primary, base);
}

p {
  color: variable-lookup(primary);
}
Run Code Online (Sandbox Code Playgroud)

这将编译为以下 css

div {
  color: blue; }

p {
  color: red; }
Run Code Online (Sandbox Code Playgroud)

您的代码存储颜色变量,但我用那些名字keysmaps

这允许使用该map-has-key方法模拟代码中变量的检查。如果返回 true,则key存在,我们可以获取值,在这种情况下将是使用的颜色map-get

更新的答案
解决您在评论中提出的问题的一种方法是定义变量并将它们用作地图中的值

$primary: #fff;
$warning: yellow; 

$colours: ( primary: $primary, 
            primary-hover: darken($primary, 5%), 
            secondary: $warning, 
            secondary-hover: darken($warning, 5%) );
Run Code Online (Sandbox Code Playgroud)

另一种方法是遍历两个列表并将颜色映射到样式

$colours: ();

$list: primary success warning; //map primary to blue, success to green and so on
$shades: blue green yellow;

@for $i from 1 through length($list) {
  $key: nth($list, $i);
  $value: nth($shades, $i);
  $colours: map-merge($colours, ($key: $value));
  $colours: map-merge($colours, (unquote($key+'-hover'): darken($value, 5% )) );
}

@debug $colours // (primary: blue, primary-hover: #0000e6, success: green, success-hover: #006700, warning: yellow, warning-hover: #e6e600)
Run Code Online (Sandbox Code Playgroud)

variable_lookup功能保持不变。

希望这能有所帮助