Get Less variable value from string

2019-09-19 20:44发布

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?

标签: css less
1条回答
时光不老,我们不散
2楼-- · 2019-09-19 21:14

(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:

查看更多
登录 后发表回答