import java.io.File
/**
* Created by FangJu on 2020/1/28
* Html DSL
*/
interface Node {
fun render(): String
}
class StringNode(val value: String) : Node {
override fun render(): String {
return value
}
}
// 父结点
class BlockNode(val name: String) : Node {
// 子节点
val children = ArrayList<Node>()
// 每个头结点对应的属性
val properties = HashMap<String, Any>()
override fun render(): String {
return """
<$name
${properties.map { "${it.key} = '${it.value}'" }.joinToString("")}>
${children.joinToString("") { it.render() }}
</$name>
""".trimIndent()
}
operator fun String.invoke(block: BlockNode.() -> Unit): BlockNode {
val node = BlockNode(this)
node.block()
this@BlockNode.children += node
return node
}
operator fun String.invoke(value: Any) {
this@BlockNode.properties[this] = value
}
operator fun String.unaryPlus() {
this@BlockNode.children += StringNode(this)
}
}
fun html(block: BlockNode.() -> Unit): BlockNode {
val html = BlockNode("html")
html.block()
return html
}
fun BlockNode.head(block: BlockNode.() -> Unit): BlockNode {
val head = BlockNode("head")
head.block()
this.children += head
return head
}
fun BlockNode.body(block: BlockNode.() -> Unit): BlockNode {
val body = BlockNode("body")
body.block()
this.children += body
return body
}
fun main() {
val htmlContent = html {
head {
"meta" {
"charset"(
"UTF-8"
)
}
}
body {
"div" {
"style"(
"""
width: 200px;
height: 200px;
line-height: 200px;
background-color: #C9394A;
text-align: center
""".trimIndent()
)
"span" {
"style"(
"""
color: white;
font-family: Microsoft YaHei
""".trimIndent()
)
+"Hello HTML DSL!!"
}
}
}
}.render()
File("Kotlin.html").writeText(htmlContent)
}
kotlin编写Html文件
最新推荐文章于 2024-05-15 13:44:40 发布