Last Updated: February 25, 2016
·
8.051K
· zaus

SASS/SCSS - Index Lookup in Loops

At the moment, SASS doesn't support 'hash' | key/value | dictionary | map structures (although it seems they will soon?). So, in order to have a clean implementation of something you'd do in Javascript like:

var colors : { red: 'rgb(rr,gg,bb)', blue: 'hsl(hh,ss,ll)', ... }
function setBgColor($el, color) {
    $el.css('background-color', colors[color]);
}

you instead must use "paired" lists:

$list: 'first', 'second', 'fourth';
$colors: red blue green brown;

(Note that I've intentionally omitted third)

Then, you could use either the SASS @each or @for loop like so:

@each $item in $list {
    $i: index($list, $item);
   .#{$item}-each {
        color: nth($colors, $i);
   }
  .btn-each-#{$i} { color: red; } // not what you intend
}

@for $i from 1 through length($list) {
  $item: nth($list, $i);

   .#{$item}-for {
        color: nth($colors, $i);
   }
  .btn-for-#{$i} { color: blue; } // not what you intend
}

Each results in the "same" CSS -- try it on codepen, but at the moment it doesn't work on jsfiddle.

Example HTML, for reference:

<h1>For</h1>
<ul>
  <li class="first-for">the first item</li>
  <li class="second-for">the second item</li>
  <li class="third-for">the third item</li>
  <li class="fourth-for">the fourth item</li>
</ul>


<ul>
  <li class="btn-for-0">the zeroth item</li>
  <li class="btn-for-1">the first item</li>
  <li class="btn-for-2">the second item</li>
  <li class="btn-for-3">the third item</li>
  <li class="btn-for-4">the fourth item</li>
</ul>

<h1>Each</h1>

<ul>
  <li class="first-each">the first item</li>
  <li class="second-each">the second item</li>
  <li class="third-each">the third item</li>
  <li class="fourth-each">the fourth item</li>
</ul>

<ul>
  <li class="btn-each-0">the zeroth item</li>
  <li class="btn-each-1">the first item</li>
  <li class="btn-each-2">the second item</li>
  <li class="btn-each-3">the third item</li>
  <li class="btn-each-4">the fourth item</li>
</ul>

2 Responses
Add your response

You can also do something similar with multidimensional lists -- http://stackoverflow.com/questions/6572588/sass-each-with-multiple-variables

over 1 year ago ·

Good use of nth and length functions :)

over 1 year ago ·