Get current index with LESS Recursion

2019-07-02 15:31发布

问题:

I'm trying to make this:

I have an array like this:

@levels:'level_one','level_two','level_three','level_four','level_five','level_six','level_seven','level_eight';

Each of those levels also has a corresponding variable which is a colour, and match a class in the list markup of the level indicator. I'm able to loop through these easily enough to generate out the background colours for each level.

I want to be able to have the heights automatically set for each item, so theoretically if I wanted to add a 9th or 10th level to the indicator, I just add the colour variable, add it to the array and add the relevant markup, without having to explicitly set the height on each class.

.for(@levels); .-each(@color) {
   @name: e(@color);
   &.@{name} {
      background:@@name;
   }
}

I'm looping through the levels like the above, but it is somehow possible to get the current index of the loop as well as the count of the @levels array to work out a percentage based height for each item? Eg. if there's 10 items, the first item is 10% in height etc etc.?

Looking forward to any suggestions!

Thanks!

回答1:

Assuming you're using for.less snippet: There's additional @i variable available in the .-each scope (the variable is implicitly inherited from .-each's caller).

So you can write this as (with unnecessary quotes removed):

@levels:
    level_one,
    level_two,
    level_three,
    level_four,
    level_five,
    level_six,
    level_seven,
    level_eight;

.for(@levels); .-each(@name) {
    &.@{name} {
        background: @@name;
        height: (100% * @i / length(@levels));
    }
}

- - -

In Modern Less you'll achieve the same using the Lists plugin where the .for-each statement has explicitly specified index variable:

@levels:
    level_one,
    level_two,
    level_three,
    level_four,
    level_five,
    level_six,
    level_seven,
    level_eight;

.for-each(@name, @i in @levels) {
    &.@{name} {
        background: @@name;
        height: @i * 100% / length(@levels);
    }
}


标签: css less