@each loop with index

41,605

Solution 1

First of all, the @each function is not from Compass, but from Sass.


To answer your question, this cannot be done with an each loop, but it is easy to convert this into a @for loop, which can do this:

@for $i from 1 through length($refcolors) {
    $c: nth($refcolors, $i);

    // ... do something fancy with $c
}

Solution 2

To update this answer: yes you can achieve this with the @each loop:

$colors-list: #111 #222 #333 #444 #555;

@each $current-color in $colors-list {
    $i: index($colors-list, $current-color);
    .stuff-#{$i} { 
        color: $current-color;
    }
}

Source: http://12devs.co.uk/articles/handy-advanced-sass/

Solution 3

Sometimes you may need to use an array or a map. I had an array of arrays, i.e.:

$list = (('sub1item1', 'sub1item2'), ('sub2item1', 'sub2item2'));

I found that it was easiest to just convert it to an object:

$list: (
    'name': 'thao',
    'age': 25,
    'gender': 'f'
);

And use the following to get $i:

@each $property, $value in $list {
    $i: index(($list), ($property $value));

The sass team also recommended the following, although I'm not much of a fan:

[...] The above code is how I'd like to address this. It can be made more efficient by adding a Sass function like range($n). So that range(10) => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). Then enumerate can become:

@function enumerate($list-or-map) {
    @return zip($list-or-map, range(length($list-or-map));
}

link.

Share:
41,605
ignacioricci
Author by

ignacioricci

Pixel-tamer and co-founder at Vulsai

Updated on July 05, 2022

Comments

  • ignacioricci
    ignacioricci about 2 years

    I was wondering if you can get an element index for the @each loop.

    I have the following code, but I was wondering if the $i variable was the best way to do this.

    Current code:

    $i: 0;
    $refcolors: #55A46A, #9BD385, #D9EA79, #E4EE77, #F2E975, #F2D368, #F0AB55, #ED7943, #EA4E38, #E80D19;
    
    @each $c in $refcolors {
        $i: $i + 1;
        #cr-#{$i} strong {
            background:$c;
        }   
    }
    
  • Joel
    Joel over 9 years
    Unfortunately this approach breaks if $colors-list contains 2 identical values (e.g. #111, #222, #111, #333). In this case index($colors-list, #111) will always return 1, so your $i values would come out as 1, 2, 1, 4. Shame as otherwise it's a very neat approach :)
  • Francisco Presencia
    Francisco Presencia over 8 years
    This is also 1-indexed instead of the common 0-index