使用 Ktor 的 HTML 构建器时,如何将部分代码提取到 Kotlin 中的局部变量中?
How do I extract parts of code into local variables in Kotlin when using Ktor's HTML builder?
我想了解 Kotlin / Ktor 中的 HTML 构建器。
example here 使用 HTML 构建器构建结果:
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
当我添加第一个(可选)参数时,它再次起作用:call.respondHtml(HttpStatusCode.OK, block)
.
当我只是尝试将正文提取到变量中时,为什么它不起作用?
我认为编译器不喜欢after 默认参数,除非它是大括号外的 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 块中,从中创建自定义组件。
我想了解 Kotlin / Ktor 中的 HTML 构建器。 example here 使用 HTML 构建器构建结果:
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
当我添加第一个(可选)参数时,它再次起作用:call.respondHtml(HttpStatusCode.OK, block)
.
当我只是尝试将正文提取到变量中时,为什么它不起作用?
我认为编译器不喜欢after 默认参数,除非它是大括号外的 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 块中,从中创建自定义组件。