我想用kotlinx生成一堆HTML文件,我想用相同的模板启动每个文件。我想为基本结构提供一个函数,并为特定的内容提供一个lamda,比如so (非工作代码):
// provide block as a div for the sub content, does not work!
private fun createHtmlPage(block : () -> DIV.()): String {
val html = createHTMLDocument().html {
head {
meta { charset = "utf-8" }
meta { name="viewport"; content="width=device-width, initial-scale=1" }
title { +"Tables" }
link(href = "https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css", "style")
}
body {
block {}
script("", "https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js") {}
}
}
return html.serialize(true)
}并像这样使用这个函数(同样是非工作代码):
private fun createIndexPage(tables: Tables) {
val indexFile = File(path, "index.html")
// call my template function with a lamda - does not work
val html = createHtmlPage {
h1 { +"Tables" }
tables.tableNames.forEach { tableName ->
a("${tableName}.html") {
+tableName
}
br
}
}
indexFile.writeText(html)
}有人能指点我怎么做吗?
附加问题
我发现项目Ktor HTML DSL存在,并且他们在kotlinx-html之上有模板支持。我应该直接使用这个库而不是kotlinx-html吗?如果没有Ktor就可以使用它吗?
发布于 2022-08-29 09:04:50
您可以在没有服务器的情况下使用ktor-server-html-builder库。下面是一个示例:
import io.ktor.server.html.*
import kotlinx.html.*
import kotlinx.html.stream.appendHTML
fun main() {
val template = LayoutTemplate().apply {
header {
+"Ktor"
}
content {
articleTitle {
+"Hello from Ktor!"
}
articleText {
+"Kotlin Framework for creating connected systems."
}
}
}
val builder = StringBuilder()
builder.appendHTML().html(block = {
with(template) { apply() }
})
println(builder.toString())
}
class LayoutTemplate: Template<HTML> {
val header = Placeholder<FlowContent>()
val content = TemplatePlaceholder<ContentTemplate>()
override fun HTML.apply() {
body {
h1 {
insert(header)
}
insert(ContentTemplate(), content)
}
}
}
class ContentTemplate: Template<FlowContent> {
val articleTitle = Placeholder<FlowContent>()
val articleText = Placeholder<FlowContent>()
override fun FlowContent.apply() {
article {
h2 {
insert(articleTitle)
}
p {
insert(articleText)
}
}
}
}我建议在kotlinx-html之上实现您自己的模板化层,因为这并不难,而且它将更好地解决您的特定问题。
https://stackoverflow.com/questions/73509811
复制相似问题