Create dynamic variables using loop in Less

Create dynamic variables using loop in Less

I hope you have gone through my previous blogs related to Less. So based on that I came up with a new blog today, in which I will explain that how you can create dynamic variables in your Less file. So here is a less code to generate dynamic variables.

 

@suffix: 'px';

.mixin-loop(10,'temp'); // this will iterate from 10 to 1

.mixin-loop (@i,@j) when (@i > 0) { //on first call, @i = 10 and @j = 'temp'

    @tmp:~"@@{j}_@{i}@{suffix}"; // it will give @temp_10px
    @{tmp}: @i/16rem;            // now in variable @temp_10px: 0.625rem

    .mixin-loop(@i - 1,@j); //calling mixin again with decrement of 1 in @i
}

 

In above example, I called a mixin with two arguments, you can add more depending on your need. So when mixin is called there is a condition in it which checks the value of @i is greater than 0 or not. If the value is greater than 0 then it flows inside and create dynamic variable and then again calls itself till when the condition become false.

In the body of mixin, I have written a line of code which is generating dynamic variable, i.e, @tmp:~”@@{j}_@{i}@{suffix}”;

Lets understand this code for its first iteration when @i=10 and @j=’temp’ and @suffix=’px’. Put the respective values of variables, i.e.

@tmp:~”@temp_10px”;       //@tmp:~”@@{j}_@{i}@{suffix}”;

now @tmp variable contains the string “@temp_10px”

Lets consider second line, i.e. @{tmp}: @i/16rem;

in this code, replace the value of @tmp variable with its value, i.e. @temp_10px : 10/16rem;

finally, @temp_10px: 0.625rem;

and then I  again called mixin with decrement of 1 in first argument so that loop continues till the condition become false. Finally following CSS will be generated from the above LESS code.

 

@temp_10px: 0.625rem;
@temp_9px: 0.5625rem;
@temp_8px: 0.5rem;
@temp_7px: 0.4375rem;
@temp_6px: 0.375rem;
@temp_5px: 0.3125rem;
@temp_4px: 0.25rem;
@temp_3px: 0.1875rem;
@temp_2px: 0.125rem;
@temp_1px: 0.0625rem;

 

You can change/modify variables name depending on your need, this is only for those who do not want no calculate the font pixels in rem unit manually. So the formula is written in it and then it generates the equivalent unit in rem from px.

So that’s it in today’s article.  Try this and if you have any query then just comment below 🙂

 

. . .

Ask a Feature