我在Less中有一些嵌套循环。 它应该为3个大小和4个方向的填充创建css规则。 代码示例:
@sizes: normal, small, large;
@size-normal: 1em;
@size-small: 0.8 * @size-normal;
@size-large: 1.2 * @size-normal;
.l-padding {
@directions: top, left, right, bottom;
.s(@i: length(@sizes)) when (@i > 0) {
.s((@i - 1));
.d(@j: length(@directions)) when (@j > 0) {
.d((@j - 1));
@dir: extract(@directions, @j);
@s: extract(@sizes, @i);
@size: "size-@{s}";
&_@{dir}_@{s} {
.l-padding-mixin(@dir, @@size);
}
}
.d();
}
.s();
}
我不知道问题出在哪里,但它编译成许多duplacates。然而,每个独立循环都可以完成它们的工作。
.l-padding_top_normal {
padding-top: 1em;
}
.l-padding_left_normal {
padding-left: 1em;
}
.l-padding_right_normal {
padding-right: 1em;
}
.l-padding_bottom_normal {
padding-bottom: 1em;
}
.l-padding_top_normal {
padding-top: 1em;
}
.l-padding_left_normal {
padding-left: 1em;
}
.l-padding_right_normal {
padding-right: 1em;
}
.l-padding_bottom_normal {
padding-bottom: 1em;
}
.l-padding_top_normal {
padding-top: 1em;
}
...
.l-padding_top_normal {
padding-top: 1em;
}
.l-padding_top_small {
padding-top: 0.8em;
}
.l-padding_left_small {
padding-left: 0.8em;
}
.l-padding_right_small {
padding-right: 0.8em;
}
.l-padding_bottom_small {
padding-bottom: 0.8em;
}
.l-padding_top_normal {
padding-top: 1em;
}
.l-padding_left_normal {
padding-left: 1em;
}
.l-padding_right_normal {
padding-right: 1em;
}
.l-padding_bottom_normal {
padding-bottom: 1em;
}
...
许多重复。任何人都可以帮忙吗?
UPD 感谢@Harry找到解决方案:
.l-padding-mixin(@direction, @size: 1em) {
padding-@{direction}: @size;
}
@sizes: normal, small, large;
@size-normal: 1em;
@size-small: 0.8 * @size-normal;
@size-large: 1.2 * @size-normal;
//==== layouts ====
.l-padding {
@directions: top, left, right, bottom;
@i: length(@sizes);
@j: length(@directions);
.d(@j) when (@j > 0) {
.d((@j - 1));
@dir: extract(@directions, @j);
@s: extract(@sizes, @i);
@size: "size-@{s}";
&_@{dir}_@{s} {
.l-padding-mixin(@dir, @@size);
}
}
.-(@i) when (@i > 0) {
.-((@i - 1));
.d(@j);
} .-(@i);
}