连接一个变量和一个字符串以引用 LESS 中的另一个变量

Concatenate a variable and a string to reference another variable in LESS

我有一大堆表示颜色的变量。例如,@Yellow-100 是淡黄色,@Purple-900 是深紫色。

我有一个 @Page-Background 变量,它当前直接指向 @Yellow-100,还有几个其他变量指向各种其他黄色阴影。

@Page-Background: @Yellow-100;

...但我想设置一个基色以在我的应用程序中使用,这样我就可以轻松地在不同颜色之间切换,而不必重命名所有这些变量。因此,我定义了以下变量:

@Base: Yellow;

我通读了LESS's Variables documentation,但它没有提到如何用一个变量和一个字符串来引用另一个变量。 @@Base 将引用 @Yellow,但 @@Base-100 不会引用 @Yellow-100@@{Base}-100@{@Base}-100.

也没有

如何通过将 Yellow 替换为 @Base 将我的 @Page-Background 变量指向我的 @Yellow-100 变量?

这里有两件事需要解决:

  1. 当我们给一个变量赋颜色名时,Less会默认将其转换为早期版本编译器中的hex值,所以最好使用引号内的值让Less实现它是一个字符串而不是颜色。这个问题 has now been addressed 因此,如果您使用的是较新版本的 Less 编译器,则可能不需要此步骤。
  2. 我们必须通过将数字连接到 @Base 变量的值来形成派生变量的名称,然后对其求值。

将两者放在一起,下面的代码应该可以工作:

@Yellow-100: #fff;

@Page-Background: ~"@{Base}-100"; /* this will form the variable name */
@Base: "Yellow";

a{
    background: @@Page-Background; 
    /*using double @ references the variable whose name is contained in @Page-Background */
}