Tell LESS to not freak out in certain special case

2019-03-02 01:53发布

问题:

Our server has a custom language-switcher for our CSS files. It recognizes certain patterns and switches left & right commands (among other things). To tell it where to switch, we use @RIGHT@ and @LEFT@ wherever needed:

div.somecls {
    margin-@RIGHT@: 15px;

    &:after {
        content: "\f061";
        font-family: FontAwesome;
        position: absolute;
        @LEFT@: 10px;
        top: 20px;
    }
}

This also extends to class names themselves:

.push-@RIGHT@ {
    /* ... */
}

Till now, I wrote a node-script that compiled the css then replaced left and right with the proper replacements. However, I'm wondering - is there's a way to tell LESS to just ignore some things and regard them as normal?

That way I could write @LEFT@ in the LESS file itself instead of overthinking it all (this would allow a lot of flexibility, especially if there are cases where I don't want the language switcher to do anything and rather use left)

回答1:

You can tell LESS to ignore characters like @ by using escaped strings like below:

It is basically like doing var a = "1+2"; in any programming language. It treats it as a string and doesn't perform any extra operations. But in LESS when we just provide "@RIGHT@", it gets printed with the quotes, to avoid the quotes we need to use the tilda character in front.

@right: ~"@RIGHT@";
@left: ~"@LEFT@";

div.somecls {
    margin-@{right}: 15px;

    &:after {
        content: "\f061";
        font-family: FontAwesome;
        position: absolute;
        border-@{left}: 10px;
        top: 20px;
    }
}
div.@{left}{
  color: blue;
}

Demo


Update:

As mentioned in comments, earlier the above method would not work when the property-value pair is like @{left}: 10px. That is, when compiled it would not produce output as @LEFT@: 10px. This issue has now been fixed.



标签: css less