I'm currently grappling with utilizing a loop to generate customized CSS using predefined Less variables. As I am transitioning from SCSS to Less, I could benefit from an extra set of eyes as I am having trouble finding a suitable example.
Imagine you have Less code like this (although in reality, my less vars are stored in a separate file and imported using @import
before the loop);
@spacing-xsmall: .25rem; // 4px
@spacing-small: .5rem; // 8px
@spacing-medium: 1rem; // 16px
@spacing-medium-large: 1.5rem; // 24px
@spacing-large: 2rem; // 32px
@spacing-xlarge: 2.5rem; // 40px
@spacing-xxlarge: 4rem; // 64px
@sizes: xsmall, small, medium, medium-large, large, xlarge, xxlarge;
.init-spacing(@i) when (@i > 0) {
@size: extract(@sizes, @i);
@space: ~"@spacing-@{size}";
.margin-@{size} { margin: @space }
.padding-@{size} { padding: @space; }
.init-spacing(@i - 1);
}
.init-spacing(length(@sizes));
This produces an output like this;
.margin-xxlarge {
margin: @spacing-xxlarge;
}
.padding-xxlarge {
padding: @spacing-xxlarge;
}
....
But ideally, in the CSS output, I would prefer to display the actual variable VALUE instead, resulting in something like;
.margin-xxlarge {
margin: 4rem;
}
.padding-xxlarge {
padding: 4rem;
}
....
Is there a way to achieve this with Less? While I suspect that string interpolation might be causing issues, I am struggling to find a solution by reading the documentation.
Here's a Codepen link for experimenting with a reproducible situation illustrating the problem.
I attempted to follow this answer, but the output only displays something like
.class { margin: [object, object] }
. I came across similar solutions, but they didn't address my specific scenario where I need to loop through an array incorporating complex variables rather than simple index numbers. It seems like I am missing some crucial details to create the desired results in a more generic manner so that I can apply it to other comparable cases.