Variable from string interpolation returns a non unit value

ぃ、小莉子 提交于 2019-12-01 11:05:57

问题


This is the first time I'mn building a site using LESS and encountered a problem best described by the code below:

@section-row-padding-size-xs: 30px;
@section-row-padding-size-sm: 50px;
@section-row-padding-size-md: 100px;
@section-row-padding-size-lg: 140px;

.section-row-padding( @size ) {
    @padding-size: ~"@{section-row-padding-size-@{size}}";

    .section-row {
        padding: @padding-size 0;

        &.quarter-padding-top {
            padding-top: @padding-size * 0.25;
        }

        &.quarter-padding-bottom {
                padding-bottom: @padding-size * 0.25;
        }

        &.half-padding-top {
            padding-top: @padding-size * 0.5;
        }

        &.half-padding-bottom {
            padding-bottom: @padding-size * 0.5;
        }

        &.three-quarters-padding-top {
            padding-top: @padding-size * 0.75;
        }

        &.three-quarters-padding-bottom {
            padding-bottom: @padding-size * 0.75;
        }
    }
}

All this code does is outputting the right padding sizes for use in media queries.

Any call to .section-row-padding() either with lg, md, sm and xs argument should output the appropriate padding sizes.

The problem is caused by the @padding-size not intepreted as a px unit but rather as a string. I've tried several interpolation methods, but none of them works. isnumber( @padding-size ) outputs false and istring( @padding-size ) outputs true. @padding-size + 0px does not work either, it says Operation on an invalid type.

Is there anything that I missed?

Thanks for your time and answer!


回答1:


Nested interpolation i.e. ~"@{section-row-padding-size-@{size}}" is not officially supported in Less. (It works in current versions but may stop to work at any moment eventually).

The correct method to achieve what you want is:

.section-row-padding(@size) {
    @var-name: "section-row-padding-size-@{size}";
    @padding-size: @@var-name;
    padding: (@padding-size * 2);
}

or shorter:

.section-row-padding(@size) {
    @padding-size: "section-row-padding-size-@{size}";
    padding: (@@padding-size * 2);
}

See "variable references" for @@ meaning.

The problem is caused by the @padding-size not interpreted as a px unit but rather as a string.

Exactly. Using ~"" is like saying to the compiler "do not interpreter this value, it's just some string with whatever value I want you to pass through". Thus the type of the value returned by ~"@{section-row-padding-size-@{size}}" in your example is not a number and it can't be used with arithmetic operations (hence: "Operation on an invalid type").

(A few links for "why ~"" should be avoided whenever possible": 1, 2, 3, 4 etc.).



来源:https://stackoverflow.com/questions/21932983/variable-from-string-interpolation-returns-a-non-unit-value

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