Sass in the Real World: book 2 of 4

Improvements with lists

Let's review the code of _icons.scss and its repeating pattern:

.#{$fa-css-prefix}-glass:before { content: $fa-var-glass; }
.#{$fa-css-prefix}-music:before { content: $fa-var-music; }
.#{$fa-css-prefix}-search:before { content: $fa-var-search; }
.#{$fa-css-prefix}-envelope-o:before { content: $fa-var-envelope-o; }

The repeating model can be written like this:

..#{$fa-css-prefix}-$ICON_VAR:before { content: $ICON-VALUE }

Where $ICON_VAR are the names set in the repeating pattern in _variables.scss file like $fa-var-adjust: "\f042";. The adjust part of it constitutes the $ICON_VAR value. The $ICON_VALUE si the value of the set variable which in our example will be "\f042".

Here is where we can use lists to help us out. We can put all the icon names in a list. Let's try it with the above example segment:

$icons: glass music search envelope-o;

Now that we have the icon names in a list, we can use a @each loop to build _icons.scss:

@each $icon in $icons {
    .#{$fa-css-prefix}-#{$icon}:before {

However this list will give only half of the information that we need which is the name of the icons, we also need the value of the icons. We can re-write the list to include the values of the icons also.

$icons: (glass "\f000") (music "\f001") (search "\f002") (envelope-o "\f003");

What we have done here by using the paraenthesis, we are creating a list of lists. As we loop through the $icons list, we will get a list consisting of two items. At this point, we will take advantage of nth() (nth function reference) function to extract the icon name and value. So, our @each loop can be re-written as such:

@each $icon in $icons {
    .#{$fa-css-prefix}-#{nth($icon, 1)}:before {
        content: nth($icon, 2);

The above setup will give us the same results, but in a better and much more organized manner. However we are not done yet, we can further optimize and organize our code using maps which we will explain in the next section.