create simple html builder using Golang
Here is video step to step how to create html builder in golang
package html
type Node interface {
Html() string
}
Implement Node in Div tag
package html
type DIV struct {
Child []Node
Value string
}
func (d DIV) Html() string {
output := "<div>"
output += d.Value
if d.Child != nil {
for _, node := range d.Child {
output += node.Html()
}
}
output += "</div>"
return output
}
func (d *DIV) Add(node Node) *DIV {
/*
<div>
<div>child 1</div>
</div>
*/
d.Child = append(d.Child, node)
return d
}
Example
package main
import "github.com/tabvn/html"
func main() {
container := html.DIV{
Child: []html.Node{
html.DIV{Value: "This is content of child 1"},
},
}
container.Add(html.DIV{Value: "Child 2"})
ul := html.UL{
Child: []html.Node{
html.LI{Value: "List item 1"},
},
}
li := html.LI{Value: "List item 2"}
li.Add(html.A{Value: "Click here", URL: "http://drupalexp.com"})
ul.Add(li)
container.Add(ul)
println(container.Html())
}