ktor - 有没有办法将子模板 Template<FlowContent> 序列化为 txt/html?

ktor - is there a way to serialize sub-template Template<FlowContent> to txt/html?

我在我的 ktor 项目中使用 HTML DSL 作为模板引擎。 我正在尝试将其中一个子模板模板作为文本响应发送(我不想发送完整的 HtmlTemplate)。

到目前为止我得到了以下结果 - 为了让它工作我必须将我的 TestTemplate 包装在另一个 div:

fun Route.test() {
    get("/test") {
        call.respondText(
            buildString {
                appendHTML().div {
                    insert(TestTemplate(), TemplatePlaceholder())
                }
            }
        )
    }
}

这给了我以下响应(内部 div 是我的 TestTemplate):

<div>
  <div>this is the element I want to get, without the outer element</div>
</div>

我想得到的只是测试模板:

<div>this is the element I want to get, without the outer element</div>

有没有办法使用 HTML DSL 在 ktor 中实现它?

您可以使用 HTMLStreamBuilder<StringBuilder> 类型参数而不是 FlowContent 为模板创建 class 以构建不带任何标签的最终 HTML 字符串(FlowContent继承Tag接口)。

import io.ktor.application.*
import io.ktor.html.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import kotlinx.html.*
import kotlinx.html.stream.HTMLStreamBuilder

suspend fun main() {
    embeddedServer(Netty, port = 3333) {
        routing {
            get("/test") {
                val builder = StringBuilder()
                val html: HTMLStreamBuilder<StringBuilder> = HTMLStreamBuilder(builder, prettyPrint = true, xhtmlCompatible = false)
                html.insert(TestTemplate(), TemplatePlaceholder())
                call.respondText(html.finalize().toString())
            }
        }
    }.start()
}

class TestTemplate : Template<HTMLStreamBuilder<StringBuilder>> {
    val articleTitle = Placeholder<FlowContent>()
    val articleText = Placeholder<FlowContent>()

    override fun HTMLStreamBuilder<StringBuilder>.apply() {
        article {
            h2 {
                insert(articleTitle)
            }
            p {
                insert(articleText)
            }
        }
    }
}