Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output LESS variable name as string

Tags:

css

less

I'm trying to reference a variable name as an actual string of text within a content property, rather than the value of the variable.

For context, I'm trying to set up a color palette for a style guide. Colors are defined as variables and then listed using the content property. @rocketRed may compile as "#ff0048", but how do I compile @rocketRed as "@rocketRed"?

And if that's not enough, it's probably further complicated by me trying to pass the variable through a mixin. Otherwise it'd sort of defeat the purpose.

Here's an example:

@rocketRed:#ff0048;

.mixin(@color) {
  &:before {content: "@color"};
  &:after {content: "@{color}"};
}

.test {
  .mixin(@rocketRed)
}

Which compiles to

.test:before {
  content: "@color";
}
.test:after {
  content: "#ff0048";
}

The :before clearly doesn't work. What I'd really like that to compile to is:

content: "@rocketRed";

I suppose part of the problem is the variables automatically compile. @color -> @rocketRed -> #ff0048. Somehow I'd need to just reference what @color is referencing, and stop it there, by converting it to a string.

This is the closest thing I've come across, which really isn't too applicable, but I'd imagine the solution (if at all possible) would be somewhat similar: Use selector name as variable in LESS mixin

I realize I'm probably pushing some boundaries on how variables work, but sometimes pushing boundaries works out!

like image 575
Chase Avatar asked Mar 16 '23 13:03

Chase


1 Answers

No, this is simply impossible. If you really need something like this do it in reverse (i.e. by converting a string to the corresponding variable value), e.g.:

@rocketRed: #ff0048;

.mixin(@color) {
  color: @@color;                // variable value
  &:before {content: "@{color}"} // variable name
}

.usage {
    .mixin(rocketRed);
}

Or alternatively (if you like more quotes in your code):

@rocketRed: #ff0048;

.mixin(@color) {
  color: @@color;            // variable value
  &:before {content: @color} // variable name
}

.usage {
    .mixin("rocketRed");
}

---

Assuming you need this for some debug/logging purposes, it can be optimized to consume only one pseudo-element:

@rocketRed: #ff0048;

.mixin(@color) {
    &:before {
        content: %("@%a: %a",
            @color, @@color);
    }
}

.usage {
    .mixin(rocketRed);
}

-> css:

.usage:before {
  content: "@rocketRed: #ff0048";
}
like image 169
seven-phases-max Avatar answered Mar 28 '23 16:03

seven-phases-max