Skip to content

Instantly share code, notes, and snippets.

@dhermes
Last active November 8, 2019 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhermes/584438c2b4d7791e5696ae4f00fd8d0a to your computer and use it in GitHub Desktop.
Save dhermes/584438c2b4d7791e5696ae4f00fd8d0a to your computer and use it in GitHub Desktop.
Brief Tour of Golang `html/template`

How Do Golang HTML Templates Work?

$ go run main.go
Above
(enabled=NO) Hello World!
Below
{{- define "parent" -}}
{{- $child := child .Before .Nested -}}
{{ .Before }}
{{ template "child" $child }}
{{ .After }}
{{ end -}}
{{- define "child" -}}
(enabled={{ if .Disabled }}NO{{ else }}YES{{ end }}) {{ .Message }}
{{- end -}}
package main
import (
"fmt"
"log"
"os"
"text/template"
)
type childCtx struct {
Disabled bool
Message string
}
type nestedCtx struct {
FirstWord string
SecondWord string
}
type parentCtx struct {
Before string
After string
Nested nestedCtx
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func makeChildCtx(before string, nc nestedCtx) (childCtx, error) {
message := fmt.Sprintf("%s %s!", nc.FirstWord, nc.SecondWord)
cc := childCtx{
Disabled: before == "Above",
Message: message,
}
return cc, nil
}
func main() {
t, err := template.New("").Funcs(template.FuncMap{"child": makeChildCtx}).ParseFiles("document.txt")
check(err)
data := parentCtx{
Before: "Above",
After: "Below",
Nested: nestedCtx{
FirstWord: "Hello",
SecondWord: "World",
},
}
err = t.ExecuteTemplate(os.Stdout, "parent", data)
check(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment