are variable mixin names in LESS possible?

2019-08-04 16:33发布

What I want to do is to create a mixin that takes arguments and uses one or more of the arguments as names for other mixins to be included.

as I'm not sure about the proper terms, I'll try to explain through example:

@gradients{
    light:#fafafa; //Should these also be prefixed with @?
    dark:#888888;
}
@gradientBackground(@name,@height){
    background-image:url('../img/gradients/{@name}-{@height}.png'); //this works
    background-color:@gradients[@name];
}

.someBox{
    @gradientBackground(light;150);
}

//Expected result:
.someBox{
    background-image:url('../img/gradients/light-150.png'); //This works
    background-color:#fafafa; //This doesn't work.
}

The image works but I haven't yet figured out how to reference the appropriate color from @gradients. Is this possible at all?

1条回答
We Are One
2楼-- · 2019-08-04 17:01

I don't think you'd need @gradients variable at all. Just define your variables:

@light:#fafafa;
@dark:#888888;

Your mixin should not start with @, that defines a variable. A mixin is basically just a class.

.gradientBackground(@name:@dark, @height:500){
    background-image:url('../img/gradients/{@name}-{@height}.png');
    background-color:@name;
}

Just as an example I set the attributes for the mixin to be the @dark color and 500 for the height.

Then when you want to use your mixin in another definition it would be like so:

.somebox {
    .gradientBackground(@light, 150);
}

So at the point were you are using the mixin you can either keep the default values or pass new ones (ie: @light & 150)

Hope that helps!

查看更多
登录 后发表回答