2

I'm wondering if it's possible to create a mixin that can return a custom variable name.

For example, I have this mixin to return an rgba value.

.fadeColor(@color: #000; @opacity: 1) {
  @returnColor: rgba(red(@color), green(@color), blue(@color), @opacity);
}

I can then do something simple like:

.class {
  .fadeColor(#f00, .5);
  color: @returnColor;
}

I will get my faded red text.

Ideally what I'd like to have the mixin do is take in a name that will be the return value so I can do something like:

.class {
  .fadeColor(@myColor, #f00, .5);
  color: @myColor;
  .fadeColor(@myBG, #00f, .7);
  background-color: @myBG;
}

Is this possible? Is there a different approach that I can take to get the same result?

I know that fade would be the most workable solution in this specific example, but in general, is creating a variable from a variable a thing that can be done in LESS.

1 Answer 1

1

You can store the variable name in a variable and call it with two @@variable. You would have to store the name of the inner variable somewhere, though. You could try something like this:

.fadeColor(@name; @color: #000; @opacity: 1) {
  @return: rgba(red(@color), green(@color), blue(@color), @opacity);
}

.class1 {
    @name: return;
    .fadeColor(@name; blue; 1);
    border-color: @@name;
}

.class2 {
    @myColor: return;
    @myBG: return;
    &{
      .fadeColor(@myColor, #f00, .5);
      color: @@myColor;
    }
    &{
      .fadeColor(@myBG, #00f, .7);
      background: @@myBG;
    }
}

which will produce:

.class1 {
  border-color: #0000ff;
}
.class2 {
  color: rgba(255, 0, 0, 0.5);
  background: rgba(0, 51, 255, 0.7);
}

Probably that introduces a lot of unnecessary code. I don't know what you are trying to do, but you can probably find better ways to achieve what you want without requiring a mixin to return a value. You could, for example, send the property as a parameter:

.fadeColor(@property; @color: #000; @opacity: 1) {
    @{property}: rgba(red(@color), green(@color), blue(@color), @opacity);
}

.class2 {
    .fadeColor(color, #f00, .5);
    .fadeColor(background, #00f, .7);
}

In Less 1.7.0 you can store complete rulesets in variables (see: detached rulesets feature). You might want to experiment with it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your reply. Honestly, I don't have a terribly good use case for this sort of thing, but in the course of working on a project I just got to wondering if this was even possible.. just to have that knowledge in case it ever became useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.