-
Notifications
You must be signed in to change notification settings - Fork 0
/
html.go
59 lines (45 loc) · 1.03 KB
/
html.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package formulate
import (
"html/template"
"strings"
"golang.org/x/net/html"
)
// RenderHTMLToNode renders a html string into a parent *html.Node.
// The parent node is emptied before the data is rendered into it.
func RenderHTMLToNode(data template.HTML, parent *html.Node) error {
n, err := html.Parse(strings.NewReader(string(data)))
if err != nil {
return err
}
body := getBody(n)
for c := parent.FirstChild; c != nil; c = c.NextSibling {
parent.RemoveChild(c)
}
moveNodeChildren(body, parent)
return nil
}
// getBody finds the <body> element inside the parsed HTML tree.
func getBody(node *html.Node) *html.Node {
var body *html.Node
var f func(n *html.Node)
f = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "body" {
body = n
return
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(node)
return body
}
func moveNodeChildren(from, to *html.Node) {
c := from.FirstChild
for c != nil {
x := c
c = c.NextSibling
from.RemoveChild(x)
to.AppendChild(x)
}
}