Thursday, March 13, 2025

Intro to Ktor: The HTTP server for Kotlin

Now, if we wish to generate extra refined content material from that endpoint, like an inventory of quotes and their authors, we will change to utilizing Ktor’s HTML DSL. First, we want two extra imports, that are already a part of the venture as a result of we included the DSL within the generated venture:


import io.ktor.server.html.*
import kotlinx.html.*


And we will generate our response like so:


routing {
  get("/") {
    name.respondHtml {
      head {
        title("Quotes")
      }
      physique {
        h1 { +"Quotes to Reside By" }
        ul {
          listOf(
            "This Thoughts is the matrix of all matter." to "Max Planck",
            "All religions, arts and sciences are branches of the identical tree." to "Albert Einstein",
            "The thoughts is the whole lot. What you assume you turn out to be." to "Buddha"
          ).forEach { (quote, creator) ->
       li {
         p { +quote }
         p { +"― $creator" }
       }
     }
   }
 }

That is utilizing the HTML builder capabilities from Ktor, and it showcases a number of the flexibility in Kotlin’s useful syntax. The DSL capabilities that correspond to HTML tags are readily comprehensible, and we create the identical nested construction we might with plain HTML. In curly braces, we outline the content material nested inside every tag. It may be extra markup, textual content, variables or some mixture.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

PHP Code Snippets Powered By : XYZScripts.com