Now, if we want to generate more sophisticated content from that endpoint, like a list of quotes and their authors, we can switch to using Ktor’s HTML DSL. First, we need two more imports, which are already part of the project because we included the DSL in the generated project:
import io.ktor.server.html.*
import kotlinx.html.*
And we can generate our response like so:
routing {
get("/") {
call.respondHtml {
head {
title("Quotes")
}
body {
h1 { +"Quotes to Live By" }
ul {
listOf(
"This Mind is the matrix of all matter." to "Max Planck",
"All religions, arts and sciences are branches of the same tree." to "Albert Einstein",
"The mind is everything. What you think you become." to "Buddha"
).forEach { (quote, author) ->
li {
p { +quote }
p { +"― $author" }
}
}
}
}
This is using the HTML builder functions from Ktor, and it showcases some of the flexibility in Kotlin’s functional syntax. The DSL functions that correspond to HTML tags are readily understandable, and we create the same nested structure we would with plain HTML. In curly braces, we define the content nested inside each tag. It can be more markup, text, variables or some combination.