How can I call a mixin by reference in LESS?
Asked Answered
A

1

5

The logical way would be:

.mymixin() {
  sample_key: samplevalue;
}

@avar:  mymixin;
.@{avar}();

but I get a parse error.

Is there a way to do it?

Aidaaidan answered 12/5, 2013 at 9:56 Comment(0)
A
11

Module mixins

If you want to call a specific mixin by a reference from a variable you would need to use a parameter, as you can not dynamicaly call parametric mixins by their names. So, the closest to what you want to do, would be using module mixins.

It would look like this in LESS:

.mixin(mymixin) {
  sample_key:samplevalue;
}

.mixin(anothermixin) {
  another_key:anothervalue;
}

@avar: mymixin;
.mixin(@avar);

the output CSS will be as expected:

sample_key: samplevalue;

and if you would change @avar to anothermixin you would specifically call the second mixin.

Here makes @ScottS a great use of this approach: LESS CSS Pass mixin as a parameter to another mixin

Edit:

To elaborate the answer a bit further. Why your approach wouldn't work? The problem is in selector/rule interpolation, where the line needs to have the following structure:

.prefix-satring-@{classname} some-more-string { property:value; }

so you can not call a mixin with it as it expects a { after the selector name and also an unescaped ( is not accepted as valid syntax in rule interpolation.

Additional info:

Similarly, you can not dynamically generate property names in LESS. So you can not do anything like .myclass{-webkit-@{property}:value;}, where this is possible in Sass (another very popular preprocessor language). However, there are some workarounds for that.

Another issue, that might be of notion here is that the interpolated classes (e.g. .@{avar}{something:something;}) get directly rendered into CSS and do not exist as LESS object/mixins, that you could reuse.

Ancohuma answered 12/5, 2013 at 10:32 Comment(2)
You are passing a parameter to the mixin. What I am asking is calling a mixin whos name is the value of a variable.Aidaaidan
You can not do that in LESS. The only way how you can reference a mixin dynamically is by passing a speciffic parameter, so I think it is not really fair that you down-voted my answer.Ancohuma

© 2022 - 2024 — McMap. All rights reserved.