The Go HTML builder
Like at the beginning we said, That we don't use interpreted template language (eg go html/template) to generate html page. We think they are:
- error prone without static type enforcing
- hard to refactor
- difficult to abstract out to component
- yet another tedious syntax to learn
- not flexible to use helper functions
We like to use standard Go code. the library htmlgo is just for that.
Although Go can't do flexible builder syntax like Kotlin does, But it can also do quite well.
Consider the following code:
import (
"github.com/qor5/web/v3"
. "github.com/theplant/htmlgo"
)
func result(args ...HTMLComponent) HTMLComponent {
var converted []HTMLComponent
for _, arg := range args {
converted = append(converted, Div(arg).Class("wrapped"))
}
return HTML(
Head(
Title("XML encoding with Go"),
),
Body(
H1("XML encoding with Go"),
P().Text("this format can be used as an alternative markup to XML"),
A().Href("http://golang.org").Text("Go"),
P(
Text("this is some"),
B("mixed"),
Text("text. For more see the"),
A().Href("http://golang.org").Text("Go"),
Text("project"),
),
P().Text("some text"),
P(converted...),
),
)
}
func TypeSafeBuilderExample(ctx *web.EventContext) (pr web.PageResponse, err error) {
pr.Body = result(H5("1"), B("2"), Strong("3"))
return
}
var TypeSafeBuilderSamplePFPB = web.Page(TypeSafeBuilderExample)
var TypeSafeBuilderSamplePath = URLPathByFunc(TypeSafeBuilderExample)
It's basically assembled what Kotlin can do, Also is legitimate Go code.