https://kotlinlang.org logo
#ktor
Title
# ktor
h

Hadi

08/07/2021, 8:29 AM
Hello all, I am trying to use a function to create the HTML for my response in Ktor using the following:
Copy code
route("{year}") {
    get {
        val year = call.parameters["year"]!!.toIntOrNull()
        if (year == null) {
            call.respondText { "Year can only be an integer" }
        } else {
            val posts = PostRepo.getByDate(year)
            call.respondHtml { respondWithPostList(posts) }
       }
    }
}

fun respondWithPostList(posts: List<PostDTO>?) {
    HtmlContent {
        head { title { +"Posts" } }
        body {
            posts?.forEach { post ->
                run {
                    div {
                        h3 {+"${post.title} (${post.id})"}
                        p {+post.author.email}
                    }
                }
            }
        }
    }
}
But it does not work. However, the following works:
Copy code
route("{year}") {
    get {
        val year = call.parameters["year"]!!.toIntOrNull()
        if (year == null) {
            call.respondText { "Year can only be an integer" }
        } else {
            val posts = PostRepo.getByDate(year)
            call.respondHtml {
                head { title { +"Posts" } }
                body {
                    posts?.forEach { post ->
                       run {
                            div {
                                h3 {
                                    +"${post.title} (${post.id})"
                                }
                                p {
                                    +post.author.email
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Does anyone know what I do wrong? what is the correct way to produce HTML in a function?
a

Aleksei Tirman [JB]

08/09/2021, 9:50 AM
You did it almost right. Since
HtmlContent
returns
OutgoingContent
you can return it from
respondWithPostList
function and use the result by `call.respond`:
Copy code
// ...
call.respond(respondWithPostList(posts))
// ...

fun respondWithPostList(posts: List<PostDTO>?): OutgoingContent {
    return HtmlContent {
        // ...
    }
}
2 Views