$ go run main.go
Above
(enabled=NO) Hello World!
Below
Last active
November 8, 2019 06:16
-
-
Save dhermes/584438c2b4d7791e5696ae4f00fd8d0a to your computer and use it in GitHub Desktop.
Brief Tour of Golang `html/template`
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
{{- define "parent" -}} | |
{{- $child := child .Before .Nested -}} | |
{{ .Before }} | |
{{ template "child" $child }} | |
{{ .After }} | |
{{ end -}} | |
{{- define "child" -}} | |
(enabled={{ if .Disabled }}NO{{ else }}YES{{ end }}) {{ .Message }} | |
{{- end -}} |
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 ( | |
"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