Usage of loops is an excellent way to keep the code DRY and avoid repetition. Unlike in Sass, there are no built-in @for
or @each
directive in Less for writing loops but it can still be written using recursive mixins. A recursive mixin is nothing but a mixin which keeps calling itself.
There are four key components to a loop written using Less and they are as follows:
for([initialization]; [condition]; [final-expression])
), the guard is the [condition]
.[initialization]
as it sets the base value for the counter-like variable.[final-expression]
along with the next call.statement
in a typical for loop syntax.Below is a simple for loop written in Less that creates multiple #img*
selectors (where * is a number) and also sets the background-image
property as image*.png
.
.for-loop(@index) when (@index > 0) { /* recursive mixin with guard expression - condition */
/* the statement */
#img@{index} {
background-image: url("http://mysite.com/image@{index}.png");
}
/* end of the statement */
.for-loop(@index - 1); /* the next iteration's call - final-expression*/
}
.for-loop(3); /* the primary call - initialization */
Compiled CSS:
#img3 {
background-image: url("http://mysite.com/image3.png");
}
#img2 {
background-image: url("http://mysite.com/image2.png");
}
#img1 {
background-image: url("http://mysite.com/image1.png");
}
A for-each loop in Less has the same key components as a for loop except for the following differences:
extract()
function to extract each item in the variable based on the loop's index.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");
}