Ktor/DSL

维基教科书,自由的教学读本

Ktor 创建了一套 DSL (domain-specific language)来处理前端画面产生的逻辑

下面我们来尝试用这个系统画出页面

设置[编辑]

在 build.gradle 里面加上新的 dependencies

implementation "io.ktor:ktor-html-builder:$ktor_version"

基本用法[编辑]

下面以路径 127.0.0.1:8080/html 为例,基本画面的宣告方式如下

get("/html") {
    call.respondHtml {
        head {
            title { +"Async World" }
        }
        body {
            h1 {
                +"Title"
            }
        }
    }
}

连线进 127.0.0.1:8080/html 之后,我们就可以看到 HTML 页面了,其 HTML 原始码如下

<!DOCTYPE html>
<html>
  <head>
    <title>Async World</title>
  </head>
  <body>
    <h1>Title</h1>
  </body>
</html>

语言结构[编辑]

因为是以 Kotlin 程式语言的方式撰写,所以可以在里面加入 Kotlin 的程式

比方说

get("/test") {
    call.respondHtml {
        head {
            title { +"Async World" }
        }
        body {
            h1 {
                +"Title"
            }
            for (i in 1 .. 10) {
                p {
                    +"Title"
                }
            }
        }
    }
}

所生成的页面是

<!DOCTYPE html>
<html>
  <head>
    <title>Async World</title>
  </head>
  <body>
    <h1>Title</h1>
    <p>Title</p>
    <p>Title</p>
    <p>Title</p>
    <p>Title</p>
    <p>Title</p>
    <p>Title</p>
    <p>Title</p>
    <p>Title</p>
    <p>Title</p>
    <p>Title</p>
  </body>
</html>

样板[编辑]