【问题标题】:Kotlin: Ktor how to respond text as htmlKotlin:Ktor 如何将文本响应为 html
【发布时间】:2019-03-03 18:57:15
【问题描述】:

我想使用库 kotlin-html 来生成 html 而不是 kotlinx.html。 这个库只生成一个 html 文本:

p("A paragraph").render()
// => <p>A paragraph</p>

但我找不到如何使用 Ktor 响应 html 而不是文本

fun Routing.root() {
    get("/") {
        call.respondText {"<p>A paragraph</p>"}
    }
}

此代码将生成一个带有文本 &lt;p&gt;A paragraph&lt;/p&gt; 的页面,而不是 html-page。似乎call.respondHtml 仅适用于 kotlinx.html DSL。如何使用纯文本来做到这一点?

【问题讨论】:

    标签: kotlin ktor


    【解决方案1】:

    您可以将ContentType参数指定为ContentType.Text.HtmlrespondText

    call.respondText("<p>foo</p>", ContentType.Text.Html)
    

    如果没有提供ContentType,则默认使用ContentType.Text.Plain

    【讨论】:

      【解决方案2】:

      Ktor 有一个特殊的模块用于处理kotlinx.html,所以你可以使用

      call.respondHtml {
          head {
              title { +"Async World" }
          }
          body {
              h1(id = "title") {
                  +"Title"
              }
          }
      }
      

      在此处查看详细信息:https://ktor.io/servers/features/templates/html-dsl.html

      【讨论】:

      • 对不起,我看错了你的问题。但是,让搜索的人在这里找到答案……
      • 它对我不起作用。出错了。 “找不到具有此名称的参数:id。什么是 id?我必须先实现的变量?
      猜你喜欢
      • 2020-12-05
      • 2021-09-01
      • 2020-09-17
      • 2021-05-25
      • 2012-02-08
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多