将变量与字符串连接以形成另一个变量 [英] Concatenate variable with string to form another variable

查看:148
本文介绍了将变量与字符串连接以形成另一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@color-purple: "#ffffff"


@colors: purple, light-purple, green, light-green, red, light-red, grey, light-grey, lightest-grey;


.ColorsMixin(@i:0) when(@i =< length(@colors)){ //loop over icons array


    @color: extract(@colors, @i); //extract the icon at current index @i

    .color--@{color}{
        background: @{color-@{color}};

        &:before{
            content: "@{color}";
        }

        &:after{
            content: "\@{color-@{color}}";
        }

    }

    .ColorsMixin(@i + 1);
}


.ColorsMixin();

因此,我可以让它完成我想在

So, I can get it to do what I want to do in the

content: "\@{color-@{color}}";

部分.这将输出

content: "#ffffff";

但是,当我尝试输出@ color-purple变量作为背景时,LESS会引发错误.如果仅将其用引号引起来,它似乎才起作用,但是background属性想要的是不带引号的十六进制代码.

However, when I try to output the @color-purple variable as the background, LESS throws an error. It only seems to work if I wrap it in quotation marks, but the background property wants the hex code without the quotes around it.

这有什么窍门?

推荐答案

background: @{color-@{color}}; 

不是有效的Less语法,正确的语法应该是:

is not valid Less syntax, the proper one would be:

background: ~'@{color-@{color}}';

但是请注意,通过转义是一种肮脏的混战(虽然广泛使用,但仍然很脏). 当您直接将此类值分配给CSS属性时,它可以工作,但其他任何操作都会失败,仅因为此类值不再是颜色,而是内容未知的未加引号的字符串... 例如.以下代码将失败:

Note however, the very idea of indirectly refering to a variable values via escaping is a durty kludge (quite wide-spread but still very dirty). It works when you assign such value directly to CSS property, but it will fail for anything else, simply because such value is not a color anymore but an unquoted string with an unknown content... E.g. the following code will fail:

@color-dark-purple: #321;

div {
    @color: 'color-dark-purple';
    background: fade(~'@{color}', 50%); // error, not a color value
}

通过其名称获取变量值的适当的Less方法是变量引用",例如:

The proper Less method of getting a variable value via its name is "variable reference", e.g.:

@color-dark-purple: #321;

div {
    @color: 'color-dark-purple';
    background: fade(@@color, 50%); // OK, proper color value
}


此外,花点时间考虑一下是否真的需要将所有这些颜色作为不同变量然后单独列出这些变量名称的整个方法.通常,同时具有颜色名称和值的单个列表并不那么膨胀,而且更易于维护.


Additionally, take a time to consider if the whole approach of having all these colors as distinct variables and then having a separate list of these variables names is really what you need. Normally a single list having both color names and values is not such awfully bloating and much more maintainable.

这篇关于将变量与字符串连接以形成另一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆