在使用Ktor'时,如何将部分代码提取到Kotlin中的局部变量中;s的HTML生成器?
我试图理解Kotlin/Ktor中的HTML生成器。 使用HTML生成器生成结果:在使用Ktor'时,如何将部分代码提取到Kotlin中的局部变量中;s的HTML生成器?,kotlin,extension-methods,dsl,ktor,Kotlin,Extension Methods,Dsl,Ktor,我试图理解Kotlin/Ktor中的HTML生成器。 使用HTML生成器生成结果: call.respondHtml { head { title { +"HTML Application" } } body { h1 { +"Sample application with HTML builders" } widget { +"Widgets are just functions"
call.respondHtml {
head {
title { +"HTML Application" }
}
body {
h1 { +"Sample application with HTML builders" }
widget {
+"Widgets are just functions"
}
}
}
我试图将主体提取到一个变量中,如下所示:
val block: HTML.() -> Unit = {
head {
title { +"HTML Application" }
}
body {
h1 { +"Sample application with HTML builders" }
}
}
call.respondHtml(block)
现在我得到了以下编译错误:
Error:(37, 22) Kotlin: None of the following functions can be called with the arguments supplied:
public suspend fun ApplicationCall.respondHtml(status: HttpStatusCode = ..., versions: List<Version> = ..., cacheControl: CacheControl? = ..., block: HTML.() -> Unit): Unit defined in org.jetbrains.ktor.html
public suspend fun ApplicationCall.respondHtml(status: HttpStatusCode = ..., block: HTML.() -> Unit): Unit defined in org.jetbrains.ktor.html
Error:(37,22)Kotlin:使用提供的参数无法调用以下函数:
public suspend fun ApplicationCall.respondHtml(状态:HttpStatusCode=…,版本:List=…,cacheControl:cacheControl?=…,block:HTML.(->Unit):在org.jetbrains.ktor.HTML中定义的单位
public suspend fun ApplicationCall.respondHtml(状态:HttpStatusCode=…,block:HTML.(->单位):在org.jetbrains.ktor.HTML中定义的单位
当我添加第一个(可选)参数时,它再次工作:call.respondHtml(HttpStatusCode.OK,block)
当我试图将主体提取到变量中时,为什么它不起作用呢?我认为编译器不喜欢在默认参数之后使用强制参数,除非它是大括号之外的lambda 试着给它命名:
call.respondHtml(block = block)
顺便说一句,如果你想提取逻辑,我建议使用函数。例如:
fun HTML.headAndBody() {
head {
title { +"HTML Application" }
}
body {
h1 { +"Sample application with HTML builders" }
widget {
+"Widgets are just functions"
}
}
}
call.respondHtml {
headAndBody()
}
这样,您甚至可以向html块中添加参数,从中创建自定义组件。使用命名参数并不能解决问题,但解释是有道理的。如果不能解决问题,为什么这是公认的答案?这可能是一个很好的信息片段,但如果它实际上没有回答问题,就不应该被接受。这与使用
call.respondHtmlTemplate
方法相比如何?在我看来,这里的内容更为惯用,但它回避了一个问题,为什么Ktor支持模板系统,而您已经可以这样做了?模板更容易从Internet复制粘贴HTML,但是DSL对于条件生成和循环更为强大。我更喜欢把这两种方法混合起来。嗯,我看到的例子仍然在使用DSL,尽管我不能完全弄清楚如何让它按我想要的方式工作。这似乎是一种更直观的处理方式。我有点好奇表演会怎么样。。。但我想如果/当它成为一个问题时,我会处理的。