SASS List: Lists in Sass are kind of like an arrays, but not.

Defining a list
$cars: “TATA” “Toyota” “Maruti” “Mahindra” “BMW”;
$cars: TATA Toyota Maruti Mahindra BMW;
$cars: TATA, Toyota, Maruti, Mahindra, BMW;
$cars: “TATA”, “Toyota”, “Maruti”, “Mahindra”, “BMW”;

The lists can be nested:

$prices: TATA 55000, Toyota 100000, Maruti 300000, Mahindra 500000, BMW 2000000;

OR

$prices: (TATA 55000) (Toyota 100000) (Maruti 300000) (Mahindra 500000) (BMW 2000000);

Indexing starts at 1, not from 0, as in all other programming languages.

Everything is a list, variables, booleans, strings, anything.
This means, that list functions can be used on, say, strings:

$thing: “My name is surya”
length($thing) # Length is 1

# Drop out quotes, it’s a list
$thing: My name is surya;
length($thing) # Length is 4

List functions

Name Description
length($list) Returns the length of a list.
nth($list, $n) Returns a specific item in a list.
set-nth($list, $n, $value) Replaces the nth item in a list.
join($list1, $list2, [$separator]) Joins together two lists into one.
append($list1, $val, [$separator]) Appends a single value onto the end of a list.
zip($lists…) Combines several lists into a single multidimensional list.
index($list, $value) Returns the position of a value within a list.
list-separator(#list) Returns the separator of a list.

Accessing a list
Let us consider our cars list.
$cars: TATA Toyota Maruti Mahindra BMW;

To access an individual node of a list, use the nth() function:
nth($cars, 1)
// Results in TATA

Negative index values address elements in reverse order, starting from end.
A good trick if you need to get the last node in a list:

nth($cars, -1)
// Results in BMW

Access list with for loop

@for $i from 1 through length($cars){
.cars-#{$i}{
    &:after{
       content: "#{$i}. #{nth($cars, $i)}";
      }
   }
}

Accessing nested lists

$horses: pony #995533,horse Red,mini-horse #222,maxi-pony #882233;

It has name color pairs, in a way it looks a bit like an associative array, but it’s not.
It’s nested list, a different data type.Here’s a cool use case for it:

@each $horse in $horses {
.horses--#{hth($horse, 1)} {
        background-color: url('#{nth($horse, 2)}');
        background-image: url('img/horse-types/#{nth($horse, 1)}.png');
     }
}
Advertisements