简体   繁体   中英

Playing with LESS - optimize css generated by passing ruleset to mixin

I'm just playing with LESS lately. I wanted to generate rules for elements with numeric ID. At some stage I got code like this:

@myRule: {padding: 0;};

.myLoop(@c, @rules) when (@c >= 0) {
    .myLoop((@c - 1), @rules);
    &[id*=@{c}] { @rules(); }
    &[name*=@{c}] { @rules(); }
}

.myClass {
  .myLoop(2, @myRule);
}

which compiles to

.myClass[id*=0] {
  padding: 0;
}
.myClass[name*=0] {
  padding: 0;
}
.myClass[id*=1] {
  padding: 0;
}
.myClass[name*=1] {
  padding: 0;
}
.myClass[id*=2] {
  padding: 0;
}
.myClass[name*=2] {
  padding: 0;
}

My question is: can I in any way make it compile to sth like this:

.myClass[id*=0],
.myClass[name*=0],
.myClass[id*=1],
.myClass[name*=1],
.myClass[id*=2],
.myClass[name*=2] {
    padding: 0;
}

I was looking for something like 'extending mixins`, 'parametric extend' or 'extending ruleset' but all lead to issues that are either 'wontfix' or 'nice-to-have' :-) So I guess it's not yet possible, but I would just like to reach out to people more familiar with less then I am, to be sure.

Yes, neither extending parametric mixins nor scoped extend are possible currently, so the easiest method to achieve the result is to extend a dummy ruleset. Eg:

.my-repeat(@i, @f) when (@i >= 0) {
    .my-repeat((@i - 1), @f);
    &[id*=@{i}], &[name*=@{i}] {@f();}
}

.my-class-style {
    padding: 0;  
}

.my-class {
    .my-repeat(2, {
        &:extend(.my-class-style); 
    });
}

where .my-class-style is the dummy selector to appear in the resulting CSS too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM