问题
If I have a list in less like:
@colors: 'red' #f00, 'green' #0f0, 'blue' #00f;
I know that I can loop over the list and get the colors, but what if I want to get a specific one? Say I want to do
extract(@colors, 'green')
to get #0f0 out of the list. Is there a way to do this? If it takes a few steps instead of 1 that is fine, I am just curious if it is possible. The documentation only mentions getting an item from a list by index.
http://lesscss.org/functions/#list-functions-extract
回答1:
The Lists Less plugin has at function, so your code may be as simple as:
@colors: red #f00, green #0f0, blue #00f;
div {
color: at(@colors, green);
}
- - -
Original "Legacy Less" answer:
There's no dedicated function, but it's not a problem to write a mixin for this:
@colors:
'red' #f00,
'green' #0f0,
'blue' #00f;
usage {
.by-key(@colors, 'green');
property: @by-key;
}
// ............................
// impl.
.by-key(@array, @key, @fallback...) {
.-(length(@array));
.-(@i) when (@i > 0) {.-((@i - 1))}
.-(@i) when (@key = extract(extract(@array, @i), 1)) {
@by-key: extract(extract(@array, @i), 2);
}
.--() {@by-key: @fallback} .--;
}
What's happening inside .by-key
mixin?
.-
is a mixin to loop trough@array
to find the pair of interest..-(length(@array));
launches the first iteration (starting from the last@array
index).-(@i) when (@i > 0) ...
is the iteration mixin definition that simply invokes next iteration (until the first@array
index) - thus these two form our recursive loop..-(@i) when (@key = ...
is another iteration definition that compares current item key with the key of interest and if they match it defines the@by-key
variable we'll use as the return value.- And finally
.--() {@by-key: @fallback} .--;
is the definition and immediate call of another mixin which also defines@by-key
variable that will come into effect if no value with the specified key is found in the loop before. (hence if you call the mixin in above snippet as.by-key(@colors, 'banana', #123);
it will return#123
. This "fallback" part may be omitted and then the code will result in a error if no key is found in the array (something like "variable@by-key
is not defined").
回答2:
I dont believe you can extract by a text value, only an index.
You need to run extract
twice, first to split the inherant key value pairs in your starting array to just get an array of the values, then extract the required value:
property: extract(extract(@array, @item),2);
Where @array
is your array, and @item
is the numeric index you wish to retrive. I dont beleive you can referance text keys.
So, in your example, you would need to do:
property: extract(extract(@colors, 2),2);
来源:https://stackoverflow.com/questions/27383399/extract-item-from-css-less-list-by-name