How to make a custom class iterable in Pug?

Viewed 54

So, I have this custom paginator class, and in it I have implemented the methods [Symbol.iterator] and forEach:

class MyPaginator<T>{

  items: T[]

  //...

  [Symbol.iterator](){
    return this.items[Symbol.iterator]();
  };

  forEach(callback: (item: T, index: number) => void): void {
    return this.items.forEach(callback);
  }

  //...
}

With this, I can iterate through it in "normal" code with

for(let element of paginator) {}
// or
paginator.forEach(elements => {})

But apparently pug does not use any of those for it's each iterator, because this does not work:

ul
  each element in paginator
    li
      // something

Although this works:

ul
  each element in paginator.items
    li
      // something

Is there anything I can implement in my class so that I'm able to iterate through it in Pug without needing the .items?

1 Answers

You can use each-of with Symbol.iterator if you are using pug >= 3.

ul
  each item of paginator
    li= item
Related