Swift 库,使用 Result Builder 生成 HTML
通过组合 Node
(一个在 Element
和 String
上实现的协议) 来构建 HTML 树
let tree = Element.html(head: {
Element.metadata(charset: "UTF-8")
Element(name: "title") { "Hello world" }
}, body: {
Element.division {
Element(name: "h1") { "Hello" }
Element.paragraph { "Lorem ipsum dolor sit amet, <consectetur> adipiscing elit, sed & eiusmod." }
}
})
print(tree.renderHTML())
将输出
<html><head><meta charset="UTF-8"><title>Hello world</title></head><body><div><h1>Hello</h1><p>Lorem ipsum dolor sit amet, <consectetur> adipiscing elit, sed & eiusmod.</p></div></body></html>
条件 (if
, if else
, switch
) 和迭代 (for ... in
) 的工作方式与命令式控制流相同。
let cond1 = true
let cond2 = false
let elements = ["Lorem", "ipsum"]
let treeControlFlow = Element.html(head: {
Element.metadata(charset: "UTF-8")
Element(name: "title") { "Hello world" }
}, body: {
Element.division {
if cond1 {
Element(name: "h1") { "Hello" }
}
if cond2 {
Element(name: "h1") { "Hello" }
} else {
Element(name: "h1") { "world" }
}
ForEach(elements) { el in
Element.paragraph { el }
}
}
})
print(treeControlFlow.renderHTML())
将输出
<html><head><meta charset="UTF-8"><title>Hello world</title></head><body><div><h1>Hello</h1><h1>world</h1><p>Lorem</p><p>ipsum</p></div></body></html>
构建树时,可以修改 Element
。 有 3 个内置的修饰器,identifier
、class
和 attributes
let modifierTree = Element.division {
Element.paragraph { "Hello world" }.identifier("title")
}.class("container")
print(modifierTree.renderHTML())
将输出
<div class="container"><p id="title">Hello world</p></div>
attributes
接受一个带有 inout
属性的闭包,你可以修改这些属性
let div = Element.division {
}.attributes {
$0[.relationship] = "hello"
$0[.source] = "world"
}
print(div.renderHTML())
将输出
<div rel="hello" src="world"></div>
你可以使用 RawHTML
在树中包含原始 HTML
let rawHTMLTree = try Element.division {
try RawHTML("""
<h1>hello world</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
""")
}
将输出
<div><h1>hello world</h1><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p></div>