Get Less variable value from string

2019-09-19 21:01发布

问题:

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.)


标签: css less