Build HTML by iteration with kotlinx.html

675 Views Asked by At

I'm trying to build an HTML list using kotlinx.html by iterating over a collection, for each element in the collection I want to build an LI tag inside a UL tag.

This is what I'm trying:

fun showProducts(products: List<Product>) {
    document.getElementById(content.id)
        ?.append {
            ol {
                products.forEach {
                    this.li {
                        +it.name
                    }
                }
            }
        }
}

But I get an error in browser console:

Uncaught (in promise) TypeError: closure$products.iterator is not a function

How can I iterate over the collection and add LI tags inside the UL tag for each product passed to the function?

1

There are 1 best solutions below

0
On

maybe, instead of to use products.forEach, you can use a simple for (p in products). So the code will be:

fun showProducts(products: List<Product>) {
    document.getElementById(content.id)
        ?.append {
            ol {
                for (p in products) {
                    li {
                        +p.name
                    }
                }
            }
        }
}

see this link: https://try.kotlinlang.org/#/Kotlin%20Koans/Builders/Html%20builders/Task.kt