简体   繁体   中英

LESS mixin with loop creating background images

I need to create many background-images for boxes and i'd like to use mixins. I want to call it with 2 parameters: number and name.

I've tried that:

.counter(@counter; @name) { // outer mixin
  .counter(@counter) when (@counter > 0) {
    .counter((@counter - 1));    // next iteration
    .cat-wrapper-@{name} .cat-@{counter} {
       background-image: url('/mediafiles/@{name}/cat_@{counter}.jpg')
    }
  }
}

.counter(2;'name');

In the end I want it to output:

.cat-wrapper-name .cat-1 {
    background-image: url('mediafiles/name/cat_1.jpg');
}
.cat-wrapper-name .cat-2 {
    background-image: url('mediafiles/name/cat_2.jpg');
}

It compiles without errors but doesn't output any code. When I delete @name and just use 1 parameter @counter it works. But with 2 parameters it doesn't.

Ok the issue is you are over complicating things and missing second parameter. Your code above calls to counter which is NOT a recursive mixin, the inner recursive mixin does not get invoked at any time which is why you never see any generated code. It isn't like lot of other programming languages where it would run the code inside of the function

.counter(@counter, @name) when (@counter > 0) {
    .counter((@counter - 1), @name);    // next iteration
    .cat-wrapper-@{name} .cat-@{counter} {
       background-image: url('/mediafiles/@{name}/cat_@{counter}.jpg')
    }
}

.counter(2, name);

Recursive mixin .counter(@counter, @name: name) when (@counter > 0)

You need that second parameter and it needs to be optional, since you are not calling it .counter((@counter - 1));

OR

you pass it to the count-1 call which I have done in my above code .counter(@counter, @name) and then again at .counter((@counter - 1), @name);

You don't need the outer mixin, it serves no purpose

You can test this here https://lesstester.com/

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