Last active
November 14, 2023 13:20
-
-
Save HalCanary/61276afbab042e204e54268f6a42f065 to your computer and use it in GitHub Desktop.
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
// Go Playground: https://go.dev/play/p/ao7M54vTDRQ | |
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 NL() *html.Node { return TextNode("\n") } // Makes reading the output easier. | |
//////////////////////////////////////////////////////////////////////////////// | |
func main() { | |
html.Render(os.Stdout, | |
HtmlDocument( | |
&html.Node{Type: html.DoctypeNode, Data: "html"}, NL(), | |
Element("html", | |
Attr{"lang": "en"}, NL(), | |
Elem("head", NL(), | |
Element("meta", Attr{"charset": "utf-8"}), NL(), | |
Comment(" HELLO WORLD "), NL(), | |
Element("meta", Attr{"name": "viewport", "content": "width=device-width, initial-scale=1.0"}), NL(), | |
Elem("title", TextNode("HELLO WORLD")), NL(), | |
Elem("style", TextNode("\nbody{max-width:35em;margin:22px auto 64px auto;padding:0 8px;}\n")), NL(), | |
), NL(), | |
Elem("body", NL(), | |
Elem("h1", TextNode("HELLO,")), NL(), | |
Elem("p", TextNode("world!")), NL(), | |
), NL(), | |
), | |
), | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment