kotlin编写Html文件

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)
}
发布了110 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40833790/article/details/104099703