html_generator_example.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"os" | |
"strings" | |
"golang.org/x/net/html" | |
) | |
type Attr = map[string]string | |
func Comment(data string) *html.Node { | |
return &html.Node{Type: html.CommentNode, Data: data} | |
} | |
func TextNode(data string) *html.Node { | |
return &html.Node{Type: html.TextNode, Data: data} | |
} | |
func makeNode(nt html.NodeType, tag string, attributes Attr, children ...*html.Node) *html.Node { | |
node := &html.Node{Type: nt, Data: tag} | |
for k, v := range attributes { | |
if ns, key, found := strings.Cut(k, ":"); found { | |
node.Attr = append(node.Attr, html.Attribute{Namespace: ns, Key: key, Val: v}) | |
} else { | |
node.Attr = append(node.Attr, html.Attribute{Key: k, Val: v}) | |
} | |
} | |
for _, c := range children { | |
if c != nil { | |
node.AppendChild(c) | |
} | |
} | |
return node | |
} | |
func Element(tag string, attributes Attr, children ...*html.Node) *html.Node { | |
return makeNode(html.ElementNode, tag, attributes, children...) | |
} | |
func Elem(tag string, children ...*html.Node) *html.Node { | |
return Element(tag, nil, children...) | |
} | |
func HtmlDocument(children ...*html.Node) *html.Node { | |
return makeNode(html.DocumentNode, "", nil, children...) | |
} | |
//////////////////////////////////////////////////////////////////////////////// | |
func main() { | |
html.Render(os.Stdout, | |
HtmlDocument( | |
&html.Node{Type: html.DoctypeNode, Data: "html"}, | |
Element("html", | |
Attr{"lang": "en"}, | |
Elem("head", | |
Comment("HELLO WORLD"), | |
Element("meta", Attr{"charset": "utf-8"}), | |
Element("meta", Attr{ | |
"name": "viewport", "content": "width=device-width, initial-scale=1.0"}), | |
Elem("title", TextNode("HELLO WORLD")), | |
Elem("style", TextNode("body{max-width:35em;margin:22px auto 64px auto;padding:0 8px;}")), | |
), | |
Elem("body", | |
Elem("h1", TextNode("HELLO!")), | |
Elem("p", TextNode("world")), | |
), | |
), | |
), | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment