我正在尝试使用 kotlinx.html 构建 html 布局页面。我可以创建主页,但无法将其分解为由单独函数生成的部分。我不知道如何将在单独函数中创建的 html 包含到主文档中。
我成功地使用了 unsafe,但我认为应该有更好的方法
我的单元测试看起来像:
import kotlinx.html.*
import kotlinx.html.stream.appendHTML
import kotlinx.html.stream.createHTML
import org.junit.jupiter.api.Test
class TestHtmlDsl {
fun html(): String {
val stringBuffer = StringBuffer()
stringBuffer.appendHTML().html {
head {
}
body {
h1 { +"Head lines" }
div {
id = "main div"
div {
strong {+"sub div"}
}
getDiv1()
getDiv2()
}
}
}
return stringBuffer.toString()
}
fun getDiv1(): DIV.() -> Unit {
return {
p { +"first try" }
}
}
fun getDiv2(): String {
return createHTML().div {
p { +"second try" }
}
}
@Test
fun testHtml() {
println(html())
}
}
它产生输出:
<html>
<head></head>
<body>
<h1>Head lines</h1>
<div id="main div">
<div><strong>sub div</strong></div>
</div>
</body>
</html>
两个带段落的div都丢失了
我正在运行这个服务器端 (jvm)。我在 js 中找到了一些示例,但没有找到它们
我很想在某个地方找到更好的 kotlinx 文档
最佳答案
getDiv1()
返回函数,所以你需要调用它:getDiv1()()
getDiv2()
返回 String
,因此您需要附加它:+getDiv2()
(请注意,HTML 中的所有保留字符(如 <
、>
)都将替换为字符实体(<
、>
),所以这不太可能是你的选择)
关于html - 使用 kotlinx.html 编写 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64294635/