Extract item from list css LESS by name

If I have a smaller list:

@colors: 'red' #f00, 'green' #0f0, 'blue' #00f;

      

I know I can iterate over the list and get the colors, but what if I want to get a specific one? Let's say I want to do

extract(@colors, 'green')

      

to get # 0f0 from the list. Is there a way to do this? If it takes a few steps, not 1, that's ok, I'm just wondering if it's possible. The documentation only mentions getting an item from a list by index.

http://lesscss.org/functions/#list-functions-extract

+3


source to share


2 answers


Lists Less plugin at

, so your code can be as simple as:

@colors: red #f00, green #0f0, blue #00f;

div {
    color: at(@colors, green); 
}

      

- - -

The answer is "Less legacy":



There is no special function, but it's not a problem to write a mixin to do 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 going on inside the .by-key

mixin?

  • .-

    is a mixin to loop trough @array

    to find the pair of interest.
  • .-(length(@array));

    starts the first iteration (starting at the last index @array

    )
  • .-(@i) when (@i > 0) ...

    is a mixin iteration definition that just calls the next iteration (up to the first index @array

    ) - so these two form our recursive loop.
  • .-(@i) when (@key = ...

    is another definition of iteration that compares the current key of the element with the key of interest, and if they match, defines a variable @by-key

    that we will use as return .
  • And finally, .--() {@by-key: @fallback} .--;

    this is the definition and immediate call of another mixin, which also defines a variable @by-key

    that will take effect if a value with the specified key was not previously found in the loop. (so if you call mixin in the above snippet like .by-key(@colors, 'banana', #123);

    it will return #123

    . This "spare" part can be omitted and then the code will throw an error if no key is found in the array (something like "variable is @by-key

    not defined").
+3


source


I don't believe you can extract the text value, only the index.

You need to run extract

twice, first split the inherited key value pairs in the starting array to just get the array of values, then extract the value you want:

property: extract(extract(@array, @item),2);

      



Where @array

is your array and @item

is the numeric index you want to extract. I don't believe you can refer to text keys.

So, in your example, you would need:

property: extract(extract(@colors, 2),2);

      

+1


source







All Articles