Get Less variable value from string

时光怂恿深爱的人放手 提交于 2020-01-07 01:18:16

问题


I am trying to create a function to switch themes. When I transpile my Less to CSS, the CSS file shows the literal string interpolation rather than the variable value. The variables file looks something like:

@beach-font-color: #3d3d3d;
@ocean-font-color: #d3d3d3;

@theme: "beach";
@symbol: "@";

@currentTheme-font-color: ~"@{symbol}@{theme}-font-color";

In the stylesheet:

body { color: @currentTheme-font-color; }

The generated css produces:

body  { color: @beach-font-color; }

instead of:

body { color: #3d3d3d; }

One thing I thought might be required is:

@font: ~"@{symbol}@{theme}-font-color";

@currentTheme-font-color: ~"@{font}";

But this just produces the same results.

Why does the Less compiler use the string literal instead of the variable value?

How would I be able to get the value of the variable, going along these lines?


回答1:


(I cannot skip this to not provide an alt. answer since such "namespace emulation via variable name concatenation" is my most favourite bloody wrong Less pattern (unfortunately it is also the most widely spread one :().

Instead of emulating namespaces via using looong global variable names (doh#1 in most of programming languages and paradigms global variables are considered harmful since 1970's... :) and then assembling those variable names via the ugly concatenation syntax (doh#2, ~"@{@{@foo}}-@{bar}-seriously}?"), one can use normal namespaces with much more clean syntax:

.theme(beach) {
    @font-color: #3d3d3d;
    // other beach variables
}
.theme(ocean) {
    @font-color: #d3d3d3;
    // other ocean variables
}

@theme: beach;

.theme(@theme);

body {color: @font-color}

This is just one of possible variations (for more examples see:

  • Dynamic Variable Names with Less -> gist
  • How to thematize in lesscss
  • etc.)


来源:https://stackoverflow.com/questions/32676764/get-less-variable-value-from-string

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