I am trying to make a variadic mixin in LESS. To this end I use the following syntax for my mixin :
.mixin (@a; @rest...) {
// @rest is bound to arguments after @a
// @arguments is bound to all arguments
}
But I don't know how to manipulate @rest and read to the last parameters of the mixin.
This is my code :
.color () { }
.color (@shade) {
#id {
background-color : rgb(@shade, @shade, @shade);
}
}
.color (@shade, @rest...) {
#id {
background-color : rgb(@shade, @shade, @shade);
}
.color(@rest);
}
.color(200, 160);
As you guess, this mixin should examinate the entire list of parameters, and colour the background of my <div id="id"> with the shade of grey corresponding to the last parameter of the mixin (in this case, rgb(160, 160, 160)).
But when I compile this code with less-1.4.1.js, I get the following error :
SyntaxError: error evaluating function `rgb`:
color functions take numbers as parameters
So how to access to the second, third, fourth... parameters of the mixin ?
Thanks a lot for your advices, and have a nice week-end !
EDIT
This works perfectly, thanks a lot !
However I would like to ask an other question. Let's say that my mixin is variadic to the extent that it requires at least one parameter which has nothing to do with the rest of the arguments (e.g. a string or an other number), but which has to be processed, so that possible calls to the previous mixin could be :
.color("first argument", 200, 160);
.color(-42, 200, 160);
.color(3, 200, 160); // 3 doesn't need to be processed in the loop
In other words, the .loop should examinate all the parameters of the mixin starting from the second and apply a different process to the first argument. So I need to change the skeleton of the mixin into something like this :
.color(...) {
...; // Handling the first parameter
.loop (@arguments); // Handling the rest of the parameters
}
But in your solution, the variable @arguments contains the entire list of arguments, including the first. How to exclude it from the list, without playing on isnumber() ?
I precise that actually in my project, each of the parameters starting from the second are processed, so that :
.loop(@list, @index: 1, @shade: NULL) when not (isnumber(@list)) and (isnumber(extract(@list, @index))) {
.loop(@list, (@index + 1), extract(@list, @index));
}
becomes
.loop(@list, @index: 1, @shade: NULL) when not (isnumber(@list)) and (isnumber(extract(@list, @index))) {
.loop(@shade);
.loop(@list, (@index + 1), extract(@list, @index));
}
and this process doesn't consist in simply changing the background color of a fixed <div> ;) But I wanted to simplify my question.
Thanks a lot for your answers and precious advices !
Edit, again : what you recommend to me works perfectly, Martin. Thanks again !