5.9 C
Canberra
Wednesday, October 29, 2025

Intro to Ktor: The HTTP server for Kotlin



Now, if we need to generate extra subtle content material from that endpoint, like a listing of quotes and their authors, we are able to swap to utilizing Ktor’s HTML DSL. First, we want two extra imports, that are already a part of the challenge as a result of we included the DSL within the generated challenge:


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


And we are able to generate our response like so:


routing {
  get("/") {
    name.respondHtml {
      head {
        title("Quotes")
      }
      physique {
        h1 { +"Quotes to Dwell 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 every little thing. What you assume you turn into." to "Buddha"
          ).forEach { (quote, creator) ->
       li {
         p { +quote }
         p { +"― $creator" }
       }
     }
   }
 }

That is utilizing the HTML builder capabilities from Ktor, and it showcases among the flexibility in Kotlin’s purposeful syntax. The DSL capabilities that correspond to HTML tags are readily comprehensible, and we create the identical nested construction we’d 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

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles