Escribe para buscar…

HTML

With Ktor HTML DSL, you can respond to a client with HTML blocks.

Esta página todavía no se ha traducido — se muestra en su idioma original:English

HTML DSL

The HTML DSL integrates kotlinx.html so you can build responses as HTML blocks. You can write HTML in Kotlin, interpolate variables, and compose complex layouts with templates.

Add the ktor-server-html-builder artifact:

yaml
module.yaml
dependencies:
  - $ktor.server.htmlBuilder

Update Routing.kt:

kotlin
src/Routing.kt
fun Application.configureRouting() {
    routing {
        get("/") {
            call.respondHtml {
                body { h1 { +"Hello World!" } }
            }
        }
    }
}

Task Manager Application

You’ll incrementally build a Task Manager with:

  • Viewing all tasks in an HTML table.
  • Filtering tasks by priority and name.
  • Adding tasks via an HTML form.

Display static HTML content

Add a route that returns static HTML.

Modify Application.configureRouting() to a new route for the URL /task and the GET request type:

kotlin
src/Routing.kt
import kotlinx.html.*

fun Application.configureRouting() {
    routing {
        get("/") {
            call.respondText("Hello David!")
        }
        get("/task") {
            call.respondHtml {
                body {
                    h1 {
                        +"Tasks"
                    }
                    ul {
                        li {
                            +"Create project documentation"
                        }
                        li {
                            +"Implement user authentication"
                        }
                    }
                }
            }
        }
    }
}

A GET request is the most basic type of request in HTTP. It is triggered when the user types into the browser’s address bar or clicks a normal HTML link.

For now, you’re only returning static content. To notify the client that you will send HTML, you must set the HTTP Content Type header to “text/html.”

Navigate to http://localhost:8080/task in your browser.

You should see the list of tasks:

Tasks

  • Create project documentation
  • Implement user authentication

Implement a Task Model

  1. Inside src create a new subpackage named model.

  2. Inside the model directory create a new file Task.kt.

  3. Open the Task.kt file and add the following enum to represent priorities and a class to represent tasks:

    kotlin
    src/model/Task.kt
    package org.jetbrains.amper.ktor.model
    
        enum class Priority {
        Low, Medium, High, Vital
    }
    
    data class Task(
        val name: String,
        val description: String,
        val priority: Priority
    )

Estás leyendo una vista previa.

Inicia sesión para leer el artículo completo. Cualquier cuenta abre 4 artículos gratuitos al mes; el alumnado y el profesorado leen las páginas de su curso sin límite.

Iniciar sesión