Extract item from css LESS list by name

社会主义新天地 提交于 2019-12-06 04:57:18

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").

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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!