less Loops Writing a for-each loop


Example

A for-each loop in Less has the same key components as a for loop except for the following differences:

  • A variable which contains the list of items that has to be iterated over.
  • An extract() function to extract each item in the variable based on the loop's index.
  • A length() function to calculate the length of the array (that is, the no of items in the list) and use it in the primary mixin call (for [initialization]).

Below is a sample for-each loop written in Less that iterates through each item in the @images variable, creates a #id selector where the id is the same as the item/image name and also sets the background image property for it.

@images: cat, dog, apple, orange; /* the array list of items */

.for-each-loop(@index) when (@index > 0) { /* recursive mixin call with guard - condition */
  
  @image: extract(@images, @index); /* extract function to fetch each item from the list */
  
 /* the statement */
  #@{image} {
    background-image: url("http://mysite.com/@{image}.png");
  }
  /* end of the statement */

  .for-each-loop(@index - 1); /* the next iteration's call - final-expression */
}

.for-loop(length(@images)); /* the primary call with length() function - initialization */

Compiled CSS:

#orange {
  background-image: url("http://mysite.com/orange.png");
}
#apple {
  background-image: url("http://mysite.com/apple.png");
}
#dog {
  background-image: url("http://mysite.com/dog.png");
}
#cat {
  background-image: url("http://mysite.com/cat.png");
}