Server-side HTML generation
By Mikael Ståldal
I have been trying out htmx with Kotlin and http4k.
To use htmx, you need some way of generating HTML on the server. In Kotlin, you have plenty of options, both Kotlin specific ones and everything from the broader Java/JVM ecosystem. There are two main categories here, template languages and internal DSLs.
Given Kotlin’s good support for internal DSLs, I decided to explore that route, and try kotlinx.html and HtmlFlow. They both make great promises of encoding the entire HTML standard and enforce valid HTML at compile time. This sounds very nice in theory, but in practice they are quite a disappointment.
As you can see in my sample project with kotlinx.html, integrating it with http4k is a slightly cumbersome for complete pages, and really annoying for fragments (possibility to generate HTML fragments is crucial for htmx). It also contributes significantly to compile time.
I also wanted to give HtmlFlow a try, but it was unreasonably difficult to get it to work in a convenient way when using data binding, layout and fragments at the same time, so I gave up. Here is my incomplete and unsuccessful attempt.
My conclusion is that those advanced type-safe internal DSLs for HTML are just too heavy and complicated. They have some advantages, but it’s not worth the added complexity, cognitive load and increased compile time.
So I prefer using a template language instead. http4k have built-in support for several template languages, and I decided to try out Thymeleaf, mostly since its templates are well-formed HTML, and then you can use HTML tools and/or IDE support to ensure validity of the HTML (this works out-of-the-box in IntelliJ IDEA Ultimate). Seems to be the only one of the http4k supported templates with that property. Thymeleaf also has comprehensive support for fragments and layouts. The result became quite nice, see my sample project.